This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
summary(cars)
## speed dist
## Min. : 4.0 Min. : 2.00
## 1st Qu.:12.0 1st Qu.: 26.00
## Median :15.0 Median : 36.00
## Mean :15.4 Mean : 42.98
## 3rd Qu.:19.0 3rd Qu.: 56.00
## Max. :25.0 Max. :120.00
You can also embed plots, for example:
Note that the echo = FALSE parameter was added to the
code chunk to prevent printing of the R code that generated the
plot.
library(dslabs)
installed.packages()
library(dslabs) data(Teams) Warning message: In data(Teams) : data set ‘Teams’ not found data(teams) Warning message: In data(teams) : data set ‘teams’ not found data(murders) population Error: object ‘population’ not found murders$population
pop <- murders\(population length(pop) [1] 51 class(pop) [1] "numeric" class(murders\)state) [1] “character”
library(Lahman) Error in library(Lahman) : there is no package called ‘Lahman’ install.packages(“Lahman”)
install.packages(“tidyverse”)
library(Lahman) library(tidyverse)
Teams %>% filter(yearID %in% 1961:2001) %>% + mutate(HR_per_game = HR/G, R_per_game = R/G) %>% + lm(R_per_game ~ BB, .)
Call: lm(formula = R_per_game ~ BB, data = .)
Coefficients: (Intercept) BB
2.582186 0.003396
Teams %>% filter(yearID %in% 1961:2001 ) %>% + mutate(AB_per_game = AB/G, R_per_game = R/G) %>% + ggplot(aes(R_per_game, AB_per_game)) + + geom_point()
Teams %>% filter(yearID %in% 1961:2001 ) %>% + mutate(AB_per_game = AB/G, R_per_game = R/G) %>% + ggplot(aes(AB_per_game, R_per_game)) + + geom_line()
Teams %>% filter(yearID %in% 1961:2001 ) %>% + mutate(AB_per_game = AB/G, R_per_game = R/G) %>% + ggplot(aes(AB_per_game, R_per_game)) + + geom_point(alpha = 0.5)
Teams %>% filter(yearID %in% 1961:2001 ) %>% + ggplot(aes(AB, R)) + + geom_point(alpha = 0.5)
Teams %>% filter(yearID %in% 1961:2001 ) %>% + mutate(AB_per_game = AB/G, R_per_game = R/G) %>% + ggplot(aes(AB_per_game, R_per_game)) + + geom_point(alpha = 0.5)
?Teams
Teams %>% filter(yearID %in% 1961:2001 ) %>% + mutate(AB_per_game = AB/G, R_per_game = R/G) %>% + ggplot(aes(AB_per_game, R_per_game)) + + geom_point(alpha = 0.5)
Teams %>% filter(yearID %in% 1961:2001 ) %>% + mutate(number_of_wins_per_game = W/G, fielding_errors_per_game = E/G) %>% + ggplot(aes(number_of_wins_per_game, fielding_errors_per_game)) + + geom_point(alpha = 0.5)
Teams %>% filter(yearID %in% 1961:2001) %>% + mutate(win_rate = W / G, E_per_game = E / G) %>% + ggplot(aes(win_rate, E_per_game)) + + geom_point(alpha = 0.5)
Teams %>% filter(yearID %in% 1961:2001 ) %>% + mutate(triple_per_game = X3B/G, double_per_game = X2B/G) %>% + ggplot(aes(triple_per_game, double_per_game)) + + geom_point(alpha = 0.5)
As motivation for this course, we’ll go back to 2002 and try to build a baseball team with a limited budget. Note that in 2002, the Yankees payroll was almost $130 million, and had more than tripled the Oakland A’s $40 million budget. [][Statistics have been used in baseball since its beginnings]. Note that the data set we will be using, included in the Lahman Library, goes back to the 19th century. For example, a summary of statistics we will describe soon, the batting average, has been used to summarize a batter’s success for decades. Other statistics such as home runs, runs batted in, and stolen bases, we’ll describe all this soon, are reported for each player in the game summaries included in the sports section of newspapers.
And players are rewarded for high numbers. Although summary statistics were widely used in baseball, data analysis per se was not. These statistics were arbitrarily decided on without much thought as to whether they actually predicted, or were related to helping a team win. This all changed with Bill James. In the late 1970s, this aspiring writer and baseball fan started publishing articles describing more in-depth analysis of baseball data. He named the approach of using data to predict what outcomes best predict if a team wins [][sabermetrics]. Until Billy Beane made sabermetrics the center of his baseball operations, Bill James’ work was mostly ignored by the baseball world.
Today, pretty much every team uses the approach, and it has gone beyond baseball into other sports. In this course, to simplify the example we use, we’ll focus on predicting scoring runs. We will ignore pitching and fielding, although those are important as well. We will see how regression analysis can help develop strategies to build a competitive baseball team with a constrained budget. [][The approach can be divided into two separate data analyses. In the first, we determine which recorded player specific statistics predict runs. In the second, we examine if players were undervalued based on what our first analysis predicts.]
[][Textbook link]
The corresponding section of the textbook is the case study on Moneyball. https://rafalab.github.io/dsbook/linear-models.html#case-study-moneyball
[][Key point]
Bill James was the originator of sabermetrics, the approach of using data to predict what outcomes best predicted if a team would win.
image here
image here
We actually don’t need to understand all the details about the game
of baseball, which has over 100 rules, to see how regression will help
us find undervalued players. Here, we distill the sport to the basic
knowledge one needs to know to effectively attack the data science
challenge. Let’s get started. [][The goal of a baseball game is to score
more runs, they’re like points, than the other team]. Each team has
nine batters that bat in a predetermined order. After the ninth
batter hits, we start with the first again. Each time they come to bat,
we call it a plate appearance, PA. At each plate appearance,
the other team’s pitcher throws the ball and you try to hit it.
The plate appearance ends with a binary outcome–you either make an
out, that’s a failure and sit back down, or you don’t, that’s a
success and you get to run around the bases and potentially score a
run
(So a run means batter from Home base to 2ed base or something???).
Each team gets nine tries, referred to as innings, to score runs. Each
inning ends after three outs, after you’ve failed three times.
From these examples, we see how luck is involved in the process. When
you bat you want to hit the ball hard. If you hit it hard enough, it’s a
home run, the best possible outcome as you get at least one automatic
run. But sometimes, due to chance, you hit the ball very hard and a
defender (who is this defender???) catches it, which makes
it an out, a failure. In contrast, sometimes you hit the ball softly but
it lands just in the right place. You get a hit which is a success. The
fact that there is chance involved hints at why probability models will
be involved in all this. Now there are [][several ways to succeed].
Understanding this distinction will be important for our
analysis.
[][When you hit the ball you want to pass as many bases as possible].
There are four bases with the fourth one called home plate. Home plate
is where you start, where you try to hit. So the bases form a cycle.
[][If you get home, you score a run]
(does this means you passes 4 bases one by one under one batter???).
We’re simplifying a bit. But there are five ways you can
succeed. In other words, not making an out. First one is called
a base on balls. [][This is when the pitcher does not
pitch well and you get to go to first base]. A single is when you hit
the ball and you get to first base. A double is when you hit the ball
and you go past first base to second. Triple is when
you do that but get to third. And [][a home run is when you hit the ball
and go all the way home and score a run]. [][If you get to a base, you
still have a chance of getting home and scoring a run if the next batter
hits successfully]. While you are on base, you can also try to [][steal
a base]. If you run fast enough, you can try to go from first to second
or from second to third without the other team tagging you.
All right. Now historically, the batting average has been considered the most important offensive statistic. To define this average, we define a [][hit] and an [][at bat]. Singles, doubles, triples, and home runs are [][hits]. But remember, there’s a fifth way to be successful, the base on balls. That is not a hit. [][An at bat] is the number of times you either get a hit or make an out, bases on balls are excluded. The batting average is simply hits divided by at bats. And it is considered the main measure of a success rate. Today, in today’s game, this success rates ranges from player to player from about 20% to 38%. We refer to the batting average in thousands. So for example, if your success rate is 25% we say you’re batting 250.
One of Bill James’ first important insights is that the [][batting average ignores bases on balls but bases on balls is a success]. So a player that gets many more bases on balls than the average player might not be recognized if he does not excel in batting average. But is this player not helping produce runs? No award is given to the player with the most bases on balls. In contrast, the total number of stolen bases are considered important and an award is given out to the player with the most. But players with high totals of stolen bases also make outs as they do not always succeed.
So does a player with a high stolen base total help produce runs? Can
we use data size to determine if it’s better to pay for bases on balls
or stolen bases? [][One of the challenges in this analysis is that it is
not obvious how to determine if a player produces runs because so much
depends on his teammates]. We do keep track of the number of runs scored
by our player. But note that if you hit after someone who hits
many home runs, you will score many runs
(Super batter hit the ball far away thus you can run many bases as well, lucky player).
But these runs don’t necessarily happen if we hire this player but not
his home run hitting teammate. [][However, we can examine team level
statistics] (How ???). How do teams with many stolen bases
compare to teams with few? How about bases on balls? We have data. Let’s
examine some.
[][Textbook link]
This video corresponds to the textbook section on baseball basics. https://rafalab.github.io/dsbook/linear-models.html#baseball-basics
[][Key points]
The goal of a baseball game is to score more runs (points) than the other team.
Each team has 9 batters who have an opportunity to hit a ball with a bat in a predetermined order.
Each time a batter has an opportunity to bat, we call it a plate appearance (PA).
The PA ends with a binary outcome: the batter either makes an out (failure) and returns to the bench or the batter doesn’t (success) and can run around the bases, and potentially score a run (reach all 4 bases).
We are simplifying a bit, but there are five ways a batter can succeed (not make an out):
Base on balls (BB): the pitcher fails to throw the ball through a predefined area considered to be hittable (the strike zone), so the batter is permitted to go to first base.
Single: the batter hits the ball and gets to first base.
Double (2B): the batter hits the ball and gets to second base.
Triple (3B): the batter hits the ball and gets to third base.
Home Run (HR): the batter hits the ball and goes all the way home and scores a run.
Historically, the batting average has been considered the most important offensive statistic. To define this average, we define a hit (H) and an at bat (AB). Singles, doubles, triples, and home runs are hits. The fifth way to be successful, a walk (BB), is not a hit. An AB is the number of times you either get a hit or make an out; BBs are excluded. The batting average is simply H/AB and is considered the main measure of a success rate.
Note: The video states that if you hit AFTER someone who hits many home runs, you will score many runs, while the textbook states that if you hit BEFORE someone who hits many home runs, you will score many runs. The textbook wording is accurate.
image here
image here
plate appearance
image here
In baseball, a home run (abbreviated HR) is scored when the ball is hit in such a way that the batter is able to circle the bases and reach home safely
image here
image here
Base on ball
A single is you hit the ball and get to first base
image here
image here
baseball home run, go all the way home and score a run
baseball steal a base
Image here
batting average equation
image here
Let’s start looking at some baseball data and try to answer your questions using these data. First one, do teams that hit more home runs score more runs? We know what the answer to this will be, but let’s look at the data anyways. We’re going to examine data from 1961 to 2001. We end at 2001 because, remember, we’re back in 2002, getting ready to build a team.
We started in 1961, because that year, the league changed from 154
games to 162 games. The visualization of choice when exploring the
relationship between two variables like home runs and runs is a
scatterplot (So we can do what we prefer I suppose).
The following code shows you how to make that scatterplot. We start by
loading the Lahman library that has all these baseball statistics. And
then we simply make a scatterplot using 2d plot. Here’s a plot of runs
per game versus home runs per game.
The plot shows a very strong association–teams with more home runs tended to score more runs. Now, let’s examine the relationship between stolen bases and wins. Here are the runs per game plotted against stolen bases per game. Here, the relationship is not as clear. Finally, let’s examine the relationship between bases on balls and runs. Here are runs per game versus bases on balls per game. Although the relationship is not as strong as it was for home runs, we do see a pretty strong relationship here.
We know that, by definition, home runs cause runs, because when you
hit a home run, at least one run will score. [][Need to stufy how
baseball rules the scores or runs, is Runs and Scores the same stuff in
baseball game ???] Now it could be that home runs also cause the bases
on balls (How ??? base on balls. This is when the
pitcher does not pitch well and you get to go to first base).
If you understand the game, you will agree with me that that could be
the case. [][So it might appear that a base on ball is causing runs,
when in fact, it’s home runs that’s causing both]. This is called
[][confounding]. An important concept you will learn about. Linear
regression will help us parse all this out and quantify the
associations. This will then help us determine what players to recruit.
Specifically, we will try to predict things like how many more runs will
the team score if we increase the number of bases on balls but keep the
home runs fixed. Regression will help us answer this question, as
well.
[][Textbook link]
This video corresponds to the base on balls or stolen bases textbook section. https://rafalab.github.io/dsbook/linear-models.html#base-on-balls-or-stolen-bases
[][Key points]
The visualization of choice when exploring the relationship between two variables like home runs and runs is a scatterplot.
Code: Scatterplot of the relationship between HRs and wins
library(Lahman)
library(tidyverse)
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.6 v purrr 0.3.4
## v tibble 3.1.6 v dplyr 1.0.9
## v tidyr 1.2.0 v stringr 1.4.0
## v readr 2.1.2 v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
library(dslabs)
ds_theme_set()
Teams %>% filter(yearID %in% 1961:2001) %>%
mutate(HR_per_game = HR / G, R_per_game = R / G) %>%
ggplot(aes(HR_per_game, R_per_game)) +
geom_point(alpha = 0.5)
# Code: Scatterplot of the relationship between stolen bases and wins
Teams %>% filter(yearID %in% 1961:2001) %>%
mutate(SB_per_game = SB / G, R_per_game = R / G) %>%
ggplot(aes(SB_per_game, R_per_game)) +
geom_point(alpha = 0.5)
# Code: Scatterplot of the relationship between bases on balls and runs
Teams %>% filter(yearID %in% 1961:2001) %>%
mutate(BB_per_game = BB / G, R_per_game = R / G) %>%
ggplot(aes(BB_per_game, R_per_game)) +
geom_point(alpha = 0.5)
Image here
library(Lahman)
library(dplyr)
library(ggplot2)
#ggplot2::ds_theme_set()
Teams %>%
filter(yearID %in% 1961:2001) %>%
mutate(HR_per_game = HR/G, R_per_game = R/G) %>%
ggplot2::ggplot(aes(HR_per_game, R_per_game)) +
geom_point(alpha=0.5)
Image here
Image here
image here
caused the both
image here
[][Textbook link]
This video corresponds to the base on balls or stolen bases textbook section. https://rafalab.github.io/dsbook/linear-models.html#base-on-balls-or-stolen-bases
[][Key points]
The visualization of choice when exploring the relationship between two variables like home runs and runs is a scatterplot.
Code: Scatterplot of the relationship between HRs and wins
library(Lahman)
library(tidyverse) # this one includes dplyr and ggplot2 and many others
library(dslabs)
ds_theme_set()
Teams %>% filter(yearID %in% 1961:2001) %>%
mutate(HR_per_game = HR / G, R_per_game = R / G) %>%
ggplot(aes(HR_per_game, R_per_game)) +
geom_point(alpha = 0.5)
# Code: Scatterplot of the relationship between stolen bases and wins
Teams %>% filter(yearID %in% 1961:2001) %>%
mutate(SB_per_game = SB / G, R_per_game = R / G) %>%
ggplot(aes(SB_per_game, R_per_game)) +
geom_point(alpha = 0.5)
# Code: Scatterplot of the relationship between bases on balls and runs
Teams %>% filter(yearID %in% 1961:2001) %>%
mutate(BB_per_game = BB / G, R_per_game = R / G) %>%
ggplot(aes(BB_per_game, R_per_game)) +
geom_point(alpha = 0.5)
Comprehension Check due May 29, 2022 00:29 AWST Completed
1/1 point (graded) What is the application of statistics and data science to baseball called? Moneyball Sabermetrics The “Oakland A’s Approach” There is no specific name for this; it’s just data science.
1/1 point (graded) Which of the following outcomes is not included in the batting average? A home run A base on balls An out A single
1/1 point (graded) Why do we consider team statistics as well as individual player statistics? The success of any individual player also depends on the strength of their team. Team statistics can be easier to calculate. The ultimate goal of sabermetrics is to rank teams, not players.
1.0/1.0 point (graded) You want to know whether teams with more at-bats per game have more runs per game. What R code below correctly makes a scatter plot for this relationship?
Teams %>% filter(yearID %in% 1961:2001 ) %>% ggplot(aes(AB, R)) + geom_point(alpha = 0.5)
Teams %>% filter(yearID %in% 1961:2001 ) %>% mutate(AB_per_game = AB/G, R_per_game = R/G) %>% ggplot(aes(AB_per_game, R_per_game)) + geom_point(alpha = 0.5)
Teams %>% filter(yearID %in% 1961:2001 ) %>% mutate(AB_per_game = AB/G, R_per_game = R/G) %>% ggplot(aes(AB_per_game, R_per_game)) + geom_line()
Teams %>% filter(yearID %in% 1961:2001 ) %>% mutate(AB_per_game = AB/G, R_per_game = R/G) %>% ggplot(aes(R_per_game, AB_per_game)) + geom_point()
1.0/1.0 point (graded) What does the variable “SOA” stand for in the Teams table?
Hint: make sure to use the help file (?Teams). sacrifice out slides or attempts strikeouts by pitchers accumulated singles
1/1 point (graded)
Load the Lahman library. Filter the Teams data frame to include years from 1961 to 2001. Make a scatterplot of runs per game versus at bats (AB) per game. Which of the following is true? There is no clear relationship between runs and at bats per game. As the number of at bats per game increases, the number of runs per game tends to increase. As the number of at bats per game increases, the number of runs per game tends to decrease.
Teams %>% filter(yearID %in% 1961:2001 ) %>% + mutate(AB_per_game = AB/G, R_per_game = R/G) %>% + ggplot(aes(AB_per_game, R_per_game)) + + geom_point(alpha = 0.5)
0/1 point (graded)
Use the filtered Teams data frame from Question 6. Make a scatterplot of win rate (number of wins per game) versus number of fielding errors (E) per game. Which of the following is true? There is no relationship between win rate and errors per game. As the number of errors per game increases, the win rate tends to increase. As the number of errors per game increases, the win rate tends to decrease.This is the answer
library(dplyr) # this is for pipe %>%
library(ggplot2)
library(Lahman) # this is for Teams
#library(tidyverse) # this one includes dplyr, ggplot2 and many others
Teams %>% filter(yearID %in% 1961:2001 ) %>%
mutate(number_of_wins_per_game = W/G, fielding_errors_per_game = E/G) %>%
ggplot(aes(number_of_wins_per_game, fielding_errors_per_game)) + geom_point(alpha = 0.3)
# Explanation
When you examine the scatterplot, you can see a clear trend towards
decreased win rate with increasing number of errors per game
(before I wa using big scatter markersize). The following
code can be used to make the scatterplot:
Teams %>% filter(yearID %in% 1961:2001) %>%
mutate(win_rate = W / G, E_per_game = E / G) %>%
ggplot(aes(win_rate, E_per_game)) +
geom_point(alpha = 0.5)
Teams %>% summarise(cor(W/G, E/G))
## cor(W/G, E/G)
## 1 -0.2158873
1/1 point (graded)
Use the filtered Teams data frame from Question 6. Make a scatterplot of triples (X3B) per game versus doubles (X2B) per game. Which of the following is true? There is no clear relationship between doubles per game and triples per game. As the number of doubles per game increases, the number of triples per game tends to increase. As the number of doubles per game increases, the number of triples per game tends to decrease.
Teams %>% filter(yearID %in% 1961:2001 ) %>% + mutate(triple_per_game = X3B/G, double_per_game = X2B/G) %>% + ggplot(aes(triple_per_game, double_per_game)) + + geom_point(alpha = 0.5)
Ask your questions or make your comments about Baseball as a Motivating Example here! Remember, one of the best ways to reinforce your own learning is by explaining something to someone else, so we encourage you to answer each other’s questions (without giving away the answers, of course).
Some reminders:
Search the discussion board before posting to see if someone else has asked the same thing before asking a new question Please be specific in the title and body of your post regarding which question you’re asking about to facilitate answering your question. Posting snippets of code is okay, but posting full code solutions is not. If you do post snippets of code, please format it as code for readability. If you’re not sure how to do this, there are instructions in a pinned post in the “general” discussion forum.
library(HistData)
library(dplyr)
data("GaltonFamilies")
galton_heights <- GaltonFamilies %>%
filter(childNum == 1 & gender == 'male') %>%
select(father, childHeight) %>%
rename(son = childHeight)
galton_heights %>%
summarise(mean(father), sd(father), mean(son), sd(son))
## mean(father) sd(father) mean(son) sd(son)
## 1 69.09888 2.546555 70.45475 2.557061
# mean(father) sd(father) mean(son) sd(son)
#1 69.09888 2.546555 70.45475 2.557061
galton_heights %>%
ggplot(aes(father, son)) +
geom_point(alpha=0.5)
Up to now in this series, we have focused mainly on univariate
variables. However, in data science application it is very
common to be interested in the relationship between two or more
variables.
(Google this topic and explore a case study) We saw this in
our baseball example in which we were interested in the relationship,
for example, between bases on balls and runs. we’ll come back to this
example, but we introduce the concepts of correlation and regression
using a simpler example.
We’ll create a data set with the heights of fathers and the first sons. The actual data Galton used to discover and define regression. So we have the father and son height data. Suppose we were to summarize these data. Since both distributions are well approximated by normal distributions, we can use the two averages and two standard deviations as summaries. Here they are.
However, this summary fails to describe a very important
characteristic of the data that you can see in this figure. The trend
that the taller the father, the taller the son, is not described by the
summary statistics of the average and the standard deviation. We will
learn that the correlation coefficient is a summary of this
trend.(Interesting here how the instructor jumped in the topic of his teaching)
[][Textbook link]
The corresponding textbook section is Case Study: is height hereditary? https://rafalab.github.io/dsbook/regression.html#case-study-is-height-hereditary
[][Key points]
Galton tried to predict sons' heights based on fathers' heights.
The mean and standard errors are insufficient for describing an important characteristic of the data: the trend that the taller the father, the taller the son.
The correlation coefficient is an informative summary of how two variables move together that can be used to predict one variable using the other.
Code
# create the dataset
library(tidyverse)
library(HistData)
data("GaltonFamilies")
set.seed(1983)
# ##################################################################################################################################
galton_heights <- GaltonFamilies %>%
filter(gender == "male") %>%
group_by(family) %>%
sample_n(1) %>%
ungroup() %>%
select(father, childHeight) %>%
rename(son = childHeight)
# means and standard deviations
galton_heights %>%
summarize(mean(father), sd(father), mean(son), sd(son))
## # A tibble: 1 x 4
## `mean(father)` `sd(father)` `mean(son)` `sd(son)`
## <dbl> <dbl> <dbl> <dbl>
## 1 69.1 2.55 69.2 2.71
# scatterplot of father and son heights
galton_heights %>%
ggplot(aes(father, son)) +
geom_point(alpha = 0.5)
library(dplyr)
library(Lahman)
library(HistData)
data("GaltonFamilies")
galton_heights <- GaltonFamilies %>%
filter(childNum == 1 & gender == 'male') %>%
select(father, childHeight) %>%
rename(son=childHeight)
galton_heights %>%
summarise(mean(father), sd(father), mean(son), sd(son))
## mean(father) sd(father) mean(son) sd(son)
## 1 69.09888 2.546555 70.45475 2.557061
galton_heights %>%
ggplot(aes(father, son)) +
geom_point(alpha=0.5)
The correlation coefficient is defined for a list of pairs–x1, y1 through xn, yn– with the following formula. Here, mu x and mu y are the averages of x and y, respectively. And sigma x and sigma y are the standard deviations. The Greek letter rho is commonly used in the statistics book, to denote this correlation. The reason is that rho is the Greek letter for r, the first letter of the word regression. Soon, we will learn about the connection between correlation and regression. [][To understand why this equation does, in fact, summarize how two variables move together], consider the i-th entry of x is xi minus mu x divided by sigma x SDs away from the average. Similarly, the yi– which is paired with the xi–is yi minus mu y divided by sigma y SDs away from the average y.
If x and y are unrelated, then the product of these two quantities will be positive. That happens when they are both positive or when they are both negative as often as they will be negative. That happens when one is positive and the other is negative, or the other way around. One is negative and the other one is positive. [][This will average to about 0. The correlation is this average.]
And therefore, unrelated variables will have a correlation of
about 0 (Why ??? Sorry I didn't get it ). If
instead the quantities vary together, then we are averaging mostly
positive products. Because they’re going to be either positive times
positive or negative times negative. And we get a positive correlation.
If they vary in opposite directions, we get a negative correlation.
Another thing to know is that we can show mathematically that the correlation is always between negative 1 and 1. To see this, consider that we can have higher correlation than when we compare a list to itself. That would be perfect correlation. In this case, the correlation is given by this equation, which we can show is equal to 1. A similar argument with x and its exact opposite, negative x, proves that the correlation has to be greater or equal to negative 1. So it’s between minus 1 and 1.
To see what data looks like for other values of rho, here are six examples of pairs with correlations ranging from negative 0.9 to 0.99. When the correlation is negative, we see that they go in opposite direction. As x increases, y decreases. When the correlation gets either closer to 1 or negative 1, we see the clot of points getting thinner and thinner. When the correlation is 0, we just see a big circle of points.
[][Textbook link]
This video corresponds to the correlation coefficient section of the textbook. https://rafalab.github.io/dsbook/regression.html#the-correlation-coefficient
[][Key points]
The correlation coefficient is defined for a list of pairs
(x_1, y_1), ..., (x_n, y_n)
as the product of the standardized values:
((x_i - mu_x)/Sigma_x) * ((y_i - mu_y)/Sigma_y)
.
The correlation coefficient essentially conveys how two variables move together.
The correlation coefficient is always between -1 and 1.
Code
rho <- mean(scale(x)*scale(y)) galton_heights %>% summarize(r = cor(father, son)) %>% pull(r)
alt text here.
alt text here.
alt text here.
alt text here.
alt text here.
alt text here.
alt text here.
alt text here.
library(Lahman)
library(dplyr)
library(HistData)
data("GaltonFamilies")
galton_heights <- GaltonFamilies %>%
filter(childNum == 1 & gender == "male") %>%
select(father, childHeight) %>%
rename(son = childHeight)
galton_heights %>% summarise(cor(father, son))
## cor(father, son)
## 1 0.5007248
alt text here.
Before we continue describing regression, let’s go over a reminder
about random variability. In most data science
applications, we do not observe the population, but rather a sample. As
with the average and standard deviation, the sample correlation is the
most commonly used estimate of the population correlation. This
implies that the correlation we compute and use as a summary is a random
variable (So What ???). As an illustration, let’s
assume that the 179 pairs of fathers and sons is our entire population.
A less fortunate geneticist can only afford to take a random sample of
25 pairs. The sample correlation for this random sample can be computed
using this code. Here, the variable R is the random
variable.
[][We can run a monte-carlo simulation to see the distribution of
this random variable]. Here, we recreate R 1000 times, and plot its
histogram. We see that the expected value is the population
correlation, the mean of these Rs is 0.5, and that it has a
relatively high standard error relative to its size, SD 0.147. This is
something to keep in mind when interpreting correlations. [][It
is a random variable, and it can have a pretty large standard
error]. Also note that because the sample correlation
is an average of independent draws
(independent? average? how?), the Central Limit Theorem
actually applies. [][Therefore, for a large enough sample size N,
the distribution of these Rs is approximately normal].
The expected value we know is the population correlation. The
standard deviation is somewhat more complex to derive, but this is the
actual formula here. In our example, N equals to 25, does not appear to
be large enough to make the approximation a good one
(how to identify a good one ??? Should the standard deviation equal to a normal distribution or something ???),
as we see in this QQ-plot.
[][Textbook link]
This video corresponds to the textbook section titled: Sample correlation is a random variable. https://rafalab.github.io/dsbook/regression.html#sample-correlation-is-a-random-variable
[][Key points]
The correlation that we compute and use as a summary is a random variable.
When interpreting correlations, it is important to remember that correlations derived from samples are estimates containing uncertainty.
Because the sample correlation is an average of independent draws, the central limit theorem applies.
Code
library(dplyr)
library(Lahman)
library(HistData)
data("GaltonFamilies")
galton_heights <- GaltonFamilies %>%
filter(childNum == 1 & gender == 'male') %>%
select(father, childHeight) %>%
rename(son=childHeight)
# compute sample correlation
R <- sample_n(galton_heights, 25, replace = TRUE) %>%
summarize(r = cor(father, son))
R
## r
## 1 0.4787613
R$r
## [1] 0.4787613
# Monte Carlo simulation to show distribution of sample correlation
B <- 1000
N <- 25
R <- replicate(B, {
sample_n(galton_heights, N, replace = TRUE) %>%
summarize(r = cor(father, son)) %>%
pull(r)
})
qplot(R, geom = "histogram", binwidth = 0.05, color = I("black"))
# expected value and standard error
mean(R)
## [1] 0.4970997
sd(R)
## [1] 0.1512451
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# QQ-plot to evaluate whether N is large enough
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
data.frame(R) %>%
ggplot(aes(sample = R)) +
stat_qq() +
geom_abline(intercept = mean(R), slope = sqrt((1-mean(R)^2)/(N-2)))
library(dplyr)
library(Lahman)
library(HistData)
data("GaltonFamilies")
galton_heights <- GaltonFamilies %>%
filter(childNum == 1 & gender == 'male') %>%
select(father, childHeight) %>%
rename(son=childHeight)
# compute sample correlation
R <- sample_n(galton_heights, 25, replace = TRUE) %>%
summarize(r = cor(father, son))
R
## r
## 1 0.685367
R$r
## [1] 0.685367
# Monte Carlo simulation to show distribution of sample correlation
B <- 1000
N <- 25
R <- replicate(B, {
sample_n(galton_heights, N, replace = TRUE) %>%
summarize(r = cor(father, son)) %>%
pull(r)
})
qplot(R, geom = "histogram", bins = 5, color = I("black"))
# expected value and standard error
mean(R)
## [1] 0.4974826
sd(R)
## [1] 0.1461927
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# QQ-plot to evaluate whether N is large enough
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
data.frame(R) %>%
ggplot(aes(sample = R)) +
stat_qq() +
geom_abline(intercept = mean(R), slope = sqrt((1-mean(R)^2)/(N-2)))
library(Lahman)
library(dplyr)
library(HistData)
library(stats)
data("GaltonFamilies")
galton_heights <- GaltonFamilies %>%
filter(childNum == 1 & gender == "male") %>%
select(father, childHeight) %>%
rename(son = childHeight)
set.seed(0)
R <- sample_n(galton_heights, 25, replace=TRUE) %>%
summarize(cor(father, son))
R
## cor(father, son)
## 1 0.5889351
library(dplyr)
library(ggplot2)
B <- 1000
N <- 25
R <- replicate(B, {
sample_n(galton_heights, N, replace = TRUE) %>%
summarize(r = cor(father, son)) %>% .$r
})
# ========================================================================================================
# Using $ Operator to Access Data Frame Column.
# Using . to do what
data.frame(R) %>%
ggplot(aes(R)) + geom_histogram(binwidth=0.05, color='black')
mean(R)
## [1] 0.5040874
sd(R)
## [1] 0.1439084
library(Lahman)
library(dplyr)
library(HistData)
library(stats)
data("GaltonFamilies")
galton_heights <- GaltonFamilies %>%
filter(childNum == 1 & gender == "male") %>%
select(father, childHeight) %>%
rename(son = childHeight)
set.seed(0)
R <- sample_n(galton_heights, 25, replace=TRUE) %>%
summarize(mean(father), sd(father), mean(son), sd(son))
R
## mean(father) sd(father) mean(son) sd(son)
## 1 69.232 2.302303 70.632 2.107273
this implies that the correlation we compte and used as a summary is a random variable.png
because the sample correlation is an average of independent draws, the centeral limit theorem applies.png
[][Read this and think]
alt text here.
alt text here
1/1 point (graded) While studying heredity, Francis Galton developed what important statistical concept? Standard deviation Normal distribution Correlation Probability
1/1 point (graded) The correlation coefficient is a summary of what? The trend between two variables The dispersion of a variable The central tendency of a variable The distribution of a variable correct
1/1 point (graded)
Below is a scatter plot showing the relationship between two variables, x and y. Scatter plot of relationship between x (plotted on the x-axis) and y (plotted on the y-axis). y-axis values range from -3 to 3; x-axis values range from -3 to 3. Points are fairly well distributed in a tight band with a range from approximately (-2, 2) to (3, -3).
From this figure, the correlation between
x and y appears to be about: -0.9 -0.2 0.9 2
1/1 point (graded)
Instead of running a Monte Carlo simulation with a sample size of 25 from the 179 father-son pairs described in the videos, we now run our simulation with a sample size of 50. Would you expect the mean of our sample correlation to increase, decrease, or stay approximately the same? Increase Decrease Stay approximately the same
1/1 point (graded)
Instead of running a Monte Carlo simulation with a sample size of 25 from the 179 father-son pairs described in the videos, we now run our simulation with a sample size of 50. Would you expect the standard deviation of our sample correlation to increase, decrease, or stay approximately the same? Increase Decrease Stay approximately the same
1/1 point (graded) If X and Y are completely independent, what do you expect the value of the correlation coefficient to be? -1 -0.5 0 0.5 1 Not enough information to answer the question
1/1 point (graded)
Load the Lahman library. Filter the Teams data frame to include years from 1961 to 2001. What is the correlation coefficient between number of runs per game and number of at bats per game? correct 0.6580976
Loading You have used 1 of 10 attempts Some
1/1 point (graded)
Use the filtered Teams data frame from Question 7. What is the correlation coefficient between win rate (number of wins per game) and number of errors per game? correct -0.3396947
Loading You have used 1 of 10 attempts Some
1/1 point (graded)
Use the filtered Teams data frame from Question 7. What is the correlation coefficient between doubles (X2B) per game and triples (X3B) per game? correct -0.01157404
Loading You have used 1 of 10 attempts Some
library(Lahman)
library(tidyverse)
#library(dplyr)
#library(ggplot2)
Teams %>% filter(yearID %in% 1961:2001 ) %>%
mutate(number_of_runs_per_game = R/G, number_of_bats_per_game = AB/G) %>%
ggplot2::ggplot(aes(number_of_runs_per_game, number_of_bats_per_game)) + geom_point(alpha = 0.5)
# https://stackoverflow.com/questions/60901319/r-language-registered-s3-method-overwritten-by-data-table
library(Lahman)
library(tidyverse)
Teams %>% filter(yearID %in% 1961:2001 ) %>%
summarize(cor(R/G, AB/G))
## cor(R/G, AB/G)
## 1 0.6580976
library(Lahman)
library(tidyverse)
Teams %>% filter(yearID %in% 1961:2001 ) %>%
summarize(cor(W/G, E/G))
## cor(W/G, E/G)
## 1 -0.3396947
library(Lahman)
library(tidyverse)
Teams %>% filter(yearID %in% 1961:2001 ) %>%
summarize(cor(X2B/G, X3B/G))
## cor(X2B/G, X3B/G)
## 1 -0.01157404
Ask your questions or make your comments about Correlation here! Remember, one of the best ways to reinforce your own learning is by explaining something to someone else, so we encourage you to answer each other’s questions (without giving away the answers, of course).
Some reminders:
Search the discussion board before posting to see if someone else has asked the same thing before asking a new question
Please be specific in the title and body of your post regarding which question you're asking about to facilitate answering your question.
Posting snippets of code is okay, but posting full code solutions is not.
If you do post snippets of code, please format it as code for readability. If you're not sure how to do this, there are instructions in a pinned post in the "general" discussion forum.
Correlation is not always a good summary of the relationship between two variables. A famous example used to illustrate this are the following for artificial data sets, referred to as Anscombe’s quartet. All of these pairs have a correlation of 0.82. Correlation is only meaningful in a particular context. To help us understand when it is that correlation is meaningful as a summary statistic, we’ll try to predict the son’s height using the father’s height. This will help motivate and define linear regression. We start by demonstrating how correlation can be useful for prediction.
[][Suppose we are asked to guess the height of a randomly selected son]. Because of the distribution of the son height is approximately normal, we know that the average height of 70.5 inches is a value with the highest proportion and would be the prediction with the chances of minimizing the error. [][But what if we are told that the father is 72 inches?] Do we still guess 70.5 inches for the son? The father is taller than average, specifically he is 1.14 standard deviations taller than the average father. So shall we predict that the son is also 1.14 standard deviations taller than the average son? It turns out that this would be an overestimate.
To see this, we look at all the sons with fathers who are about 72 inches. We do this by stratifying the father’s height. We call this a conditional average, since we are computing the average son height conditioned on the father being 72 inches tall. A challenge when using this approach in practice is that we don’t have many fathers that are exactly 72. In our data set, we only have eight. If we change the number to 72.5, we would only have one father who is that height. This would result in averages with large standard errors, and they won’t be useful for prediction for this reason. But for now, what we’ll do is we’ll take an approach of creating strata of fathers with very similar heights. Specifically, we will round fathers’ heights to the nearest inch. This gives us the following prediction for the son of a father that is approximately 72 inches tall. We can use this code and get our answer, which is 71.84. This is 0.54 standard deviations larger than the average son, a smaller number than the 1.14 standard deviations taller that the father was above the average father. Stratification followed by box plots lets us see the distribution of each group. Here is that plot.
We can see that the centers of these groups are increasing with
height, not surprisingly. The means of each group appear to follow a
linear relationship
(then why we supposed to use a scatter plot to explore relationship between two variales in Exploratory Data Analysis in Python DataCamp course ? I mean many dots covering on each other, Using a boxplot would avoid this condition ???).
We can make that plot like this, with this code. See the plot and notice
that this appears to follow a line. The slope of this line appears to be
about 0.5, which happens to be the correlation between father and son
heights. This is not a coincidence. To see this
connection, let’s plot the standardized heights
(Why??? standardize? can we just use the boxplot or the grouped mean?)
against each other, son versus father, with a line that has a slope
equal to the correlation. (Think, Think, Think) [][****Read
the important comments in below standardized plot, and think about how
its all related to each other****]
Here’s the code. Here’s a plot. This line is what we call the
regression line. In a later video, we will describe Galton’s theoretical
justification for using this line to estimate conditional means. Here,
we define it and compute it for the data at hand. The regression line
for two variables, x and y, tells us that [][for every
standard deviation (sigma x) increase above the average (mu x). For x, y
grows rho standard deviations (sigma y) above the average (mu
y).]. The formula for the regression line is therefore
this one (Think, Think, Think)[][How does this comes
out???]. If there’s perfect correlation, we predict an increase that is
the same number of SDs. If there’s zero correlation, then we don’t use x
at all for the prediction of y. For values between 0 and 1, the
prediction is somewhere in between. If the correlation is negative, we
predict a reduction, instead of an increase.
It is because when the correlation is positive but lower
than the one, that we predict something closer to the mean
(it has to be the normal distribution, enough sized sample),
that we call this regression. The son regresses to the average
height.
In fact, the title of Galton’s paper was “Regression Towards Mediocrity in Hereditary Stature.” Note that if we write this in the standard form of a line, y equals b plus mx, where b is the intercept and m is the slope, the regression line has slope rho times sigma y, divided by sigma x, and intercept mu y, minus mu x, times the slope. So if we standardize the variable so they have average 0 and standard deviation 1. Then the regression line has intercept 0 and slope equal to the correlation rho. Let’s look at the original data, father son data, and add the regression line. We can compute the intercept and the slope using the formulas we just derived. Here’s a code to make the plot with the regression line. If we plot the data in standard units, then, as we discussed, the regression line as intercept 0 and slope rho. Here’s the code to make that plot.
We started this discussion by saying that we wanted to use the
conditional means to predict the heights of the sons. But then we
realized that there were very few data points in each strata. When we
did this approximation of rounding off the height of the fathers
(the boxplot), we found that these conditional means appear
to follow a line. And we ended up with the regression line
(that is if we standardize both variables - father, son).
****So the regression line gives us the prediction****. An advantage of
using the regression line is that we used all the data to estimate
just two parameters, the slope and the intercept. This makes it much
more stable. When we do conditional means, we had fewer data
points, which made the estimates have a large standard error, and
therefore be unstable. So this is going to give us a much more stable
prediction using the regression line. However, are we justified in using
the regression line to predict? Galton gives us the answer.
[][Textbook link]
There are three links to relevant sections of the textbook for this video:
correlation is not always a useful summary
https://rafalab.github.io/dsbook/regression.html#correlation-is-not-always-a-useful-summary
conditional expectation
https://rafalab.github.io/dsbook/regression.html#conditional-expectation
the regression line
https://rafalab.github.io/dsbook/regression.html#the-regression-line
[][Key points]
Correlation is not always a good summary of the relationship between two variables.
The general idea of conditional expectation is that we stratify a population into groups and compute summaries in each group.
A practical way to improve the estimates of the conditional expectations is to define strata of with similar values of x.
If there is perfect correlation, the regression line predicts an increase that is the same number of SDs for both variables. If there is 0 correlation, then we don’t use x at all for the prediction and simply predict the average . For values between 0 and 1, the prediction is somewhere in between. If the correlation is negative, we predict a reduction instead of an increase.
Code
# number of fathers with height 72 or 72.5 inches
sum(galton_heights$father == 72)
## [1] 8
sum(galton_heights$father == 72.5)
## [1] 1
# predicted height of a son with a 72 inch tall father
conditional_avg <- galton_heights %>%
filter(round(father) == 72) %>%
summarize(avg = mean(son)) %>%
pull(avg)
conditional_avg
## [1] 71.83571
# stratify fathers' heights to make a boxplot of son heights
galton_heights %>%
mutate(father_strata = factor(round(father))) %>%
ggplot(aes(father_strata, son)) +
geom_boxplot() +
geom_point()
# center of each boxplot
galton_heights %>%
mutate(father = round(father)) %>%
group_by(father) %>%
summarize(son_conditional_avg = mean(son)) %>%
ggplot(aes(father, son_conditional_avg)) +
geom_point()
# calculate values to plot regression line on original data
mu_x <- mean(galton_heights$father)
mu_y <- mean(galton_heights$son)
s_x <- sd(galton_heights$father)
s_y <- sd(galton_heights$son)
r <- cor(galton_heights$father, galton_heights$son)
m <- r * s_y/s_x
b <- mu_y - m*mu_x
r
## [1] 0.5007248
m
## [1] 0.5027904
b
## [1] 35.71249
# add regression line to plot
galton_heights %>%
ggplot(aes(father, son)) +
geom_point(alpha = 0.5) +
geom_abline(intercept = b, slope = m)
image here
image here
image here
image here
image here
conditional_avg <- galton_heights %>%
filter(round(father)==72) %>%
summarise(avg=mean(son)) %>%
.$avg
conditional_avg
## [1] 71.83571
galton_heights %>%
mutate(father_strata = factor(round(father))) %>%
ggplot(aes(father_strata, son)) +
geom_boxplot() +
geom_point()
galton_heights %>%
mutate(father=round(father)) %>%
group_by(father) %>%
summarise(son_conditional_avg = mean(son)) %>%
ggplot(aes(father, son_conditional_avg)) +
geom_point()
image here
r <- galton_heights %>%
summarise(r = cor(father, son)) %>%
.$r
galton_heights %>%
mutate(father = round(father)) %>%
group_by(father) %>%
summarise(son = mean(son)) %>%
mutate(z_father = scale(father), z_son = scale(son)) %>%
ggplot2::ggplot(aes(z_father, z_son)) +
geom_point() +
geom_abline(intercept = 0, slope = r)
# **Why do we use scale function in R?**
# When we want to scale the values in several columns of a data frame so that each column has a mean of 0 and a standard deviation of 1, we usually use the scale() function.
r <- galton_heights %>%
summarise(r = cor(father, son)) %>%
.$r
galton_heights %>%
mutate(father = round(father)) %>%
group_by(father) %>%
summarise(son = mean(son)) %>%
# mutate(z_father = father, z_son = son) %>%
# ggplot2::ggplot(aes(z_father, z_son)) +
ggplot(aes(father, son)) +
geom_point() +
geom_abline(intercept = 35.5, slope = r)
# So the reason for standardize is the intercept is easy to define, or we have to guess until its 35 or something, and also the two plot seems different, this one and the standardized one. Recall how correlation is calculated, and how scale() function standardizing the data: (x - mean(x)) / sd(x)
image here
a <- galton_heights %>%
mutate(father = round(father)) %>%
group_by(father) %>%
summarise(son = mean(son)) %>%
mutate(z_father = scale(father), z_son = scale(son))
# https://stackoverflow.com/questions/20256028/understanding-scale-in-r
a
## # A tibble: 15 x 4
## father son z_father[,1] z_son[,1]
## <dbl> <dbl> <dbl> <dbl>
## 1 62 65.2 -1.70 -2.14
## 2 64 68.1 -1.28 -1.00
## 3 65 67.6 -1.06 -1.21
## 4 66 69.2 -0.850 -0.566
## 5 67 70.0 -0.638 -0.262
## 6 68 69.2 -0.425 -0.572
## 7 69 71.2 -0.213 0.231
## 8 70 71.2 0 0.198
## 9 71 71.5 0.213 0.341
## 10 72 71.8 0.425 0.469
## 11 73 71.5 0.638 0.350
## 12 74 75.2 0.850 1.82
## 13 75 71.2 1.06 0.204
## 14 76 73.5 1.28 1.13
## 15 78 73.2 1.70 1.01
Read the below statement
image here
image here
image here
image here
image here
mu_x <- mean(galton_heights$father)
mu_y <- mean(galton_heights$son)
s_x <- sd(galton_heights$father)
s_y <- sd(galton_heights$son)
r <- cor(galton_heights$father, galton_heights$son)
m <- r * s_y / s_x
b <- mu_y - m * mu_x
r
## [1] 0.5007248
m
## [1] 0.5027904
b
## [1] 35.71249
galton_heights %>%
ggplot(aes(father, son)) +
geom_point(alpha=0.3) +
geom_abline(intercept = b, slope=m)
galton_heights %>%
ggplot(aes(scale(father), scale(son))) +
geom_point(alpha=0.3) +
geom_abline(intercept = 0, slope = r)
image here
Correlation and the regression line are widely used summary statistics. [][But it is often misused or misinterpreted]. Anscombe’s example provided toy example of data sets in which summarizing with a correlation would be a mistake. But we also see it in the media and in scientific literature as well.
The main way we motivate the use of correlation involve
what is called the bivariate normal distribution.
[][When a pair of random variables is approximated by a
bivariate normal distribution, the scatterplot looks like ovals, like
American footballs]. They can be thin. That’s when they
have high correlation. All the way up to a circle shape when they have
no correlation. We saw some examples previously. Here they are again. A
more technical way to define the bivariate normal distribution is the
following. First, this distribution is defined for
pairs (like the father - son paris used earlier).
So we have two variables, x and y. And they have paired values. They are
going to be bivariate normally distributed if the following happens.
[][If x is a normally distributed random variable, and y is also
a normally distributed random variable–and for any grouping of x that we
can define, say, with x being equal to some predetermined value, which
we call here in this formula little x–then the y’s in that group are
approximately normal as well.] If this happens, then the pair is
approximately bivariate normal. When we fix x in this way, we then refer
to the resulting distribution of the y’s in the group–defined by setting
x in this way–as the conditional distribution of y given x.
(Remember we did this before, fix father 72 inches, but the sample size is too small)
We write the notation like this for the conditional distribution and the
conditional expectation. If we think the height data is
well-approximated by the bivariate normal distribution, then we should
see the normal approximation hold for each grouping.
Here, we stratify the son height by the standardized father heights
and see that the assumption appears to hold. Here’s the code that gives
us the desired plot. Now, we come back to defining correlation. Galton
showed– using mathematical statistics– that when two variables
follow a bivariate normal distribution, then for any given x the
expected value of the y in pairs for which x is set at that value is mu
y plus rho x minus mu x divided by sigma x times sigma y. Note
that this is a line with slope rho times sigma y divided by sigma x and
intercept mu y minus n times mu x. And therefore, this is the same as
the regression line we saw in a previous video.
(Now you must understand the slope difference between standalized vairable and non-standarilized vaiable in father son case we did in prevrious chapter)
That can be written like this. So in summary, if our data is
approximately bivariate, then the conditional expectation–which is the
best prediction for y given that we know the value of x–is given by the
regression line.
[][Textbook link]
This video corresponds to the textbook section on the bivariate normal distribution (advanced). https://rafalab.github.io/dsbook/regression.html#bivariate-normal-distribution-advanced
[][Key points]
When a pair of random variables are approximated by the bivariate normal distribution, scatterplots look like ovals. They can be thin (high correlation) or circle-shaped (no correlation).
When two variables follow a bivariate normal distribution, computing the regression line is equivalent to computing conditional expectations.
We can obtain a much more stable estimate of the conditional expectation by finding the regression line and using it to make predictions.
Code
galton_heights %>%
mutate(z_father = round((father - mean(father)) / sd(father))) %>%
filter(z_father %in% -2:2) %>%
ggplot() +
stat_qq(aes(sample = son)) +
facet_wrap( ~ z_father)
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# What are we doing here?
# https://towardsdatascience.com/q-q-plots-explained-5aa8495426c0?gi=409ca0cd036
image here
image here
image here
image here
images here
images here
image here
image here
image here
galton_heights %>%
#mutate(z_father=round((father-mean(father))/sd(father))) %>% # we can scale it manually or use scale() function
mutate(z_father = round(scale(father))) %>%
filter(z_father %in% -2:2) %>%
ggplot2::ggplot() +
stat_qq(aes(sample=son)) +
facet_wrap(~z_father)
# What does a QQ plot show?
# The purpose of the quantile-quantile (QQ) plot is to show if two data sets come from the same distribution. Plotting the first data set's quantiles along the x-axis and plotting the second data set's quantiles along the y-axis is how the plot is constructed.
# https://math.illinois.edu/system/files/inline-files/Proj9AY1516-report2.pdf
# Where does above formula comes from???
image here
image here
image here
image here
image here
So this video is recorded long times ago, how interesting)The equation shown at 0:10 is for the standard deviation of the conditional distribution, not the variance. **The variance is the standard deviation squared**. See the notes below the video for more clarification.
(The theory we’ve been
describing also tells us that the standard deviation of the conditional
distribution that we described in a previous video is Var
(
Correction: The equation shown at 0:10 is for the standard deviation of the conditional distribution, not the variance)
of Y given X equals sigma y times the square root of 1 minus rho
squared. This is where statements like x explains such and such percent
of the variation in y comes from. Note that the variance of y is sigma
squared. That’s where we start. If we condition on x, then the
variance goes down to 1 minus rho squared times sigma squared
y. So from there, we can compute how much the variance has gone
down. It has gone down by rho squared times 100%. So the correlation and
the amount of variance explained are related to each other. But it is
important to remember that the variance explained statement only makes
sense when the data is by a bivariate normal distribution.
[][Read all the course material and thinking, then trying to answer your questions, its a good way of learning, and thinking]
[][Textbook link]
This video corresponds to the textbook section on variance explained. # https://rafalab.github.io/dsbook/regression.html#variance-explained
[][Key points]
Conditioning on a random variable X can help to reduce variance of response variable Y.
The standard deviation of the conditional distribution is
SD(Y|X=x) = Sigma_y * SquaredRoot(1 - rho**2),
which is smaller than the standard deviation without conditioning sigma_y.
Because variance is the standard deviation squared, the variance of the conditional distribution is:
Var(Y\X=x) = Sigma_y^(2) * (1 - rho**2).
In the statement "X explains such and such percent of the variability," the percent value refers to the variance. The variance decreases by \(\rho^2\) percent.
The “variance explained” statement only makes sense when the data is approximated by a bivariate normal distribution.
# Where does above equation comes from ???
image here
image here
image here
image here
image here
We computed a regression line to predict the son’s height from the
father’s height. We used these calculations–here’s the code–to get the
slope and the intercept. This gives us the function that the conditional
expectation of y given x is 35.7 plus 0.5 times x. So, what if we wanted
to predict the father’s height based on the son’s? It is important to
know that this is not determined by computing the inverse function of
what we just saw, which would be this equation here. [][We need to
compute the expected value of x given y]. This gives us another
regression function altogether, with slope and intercept computed like
this. (How did this comes from??) So now we get that the
expected value of x given y, or the expected value of the father’s
height given the son’s height, is equal to 34 plus 0.5 y, a different
regression line.
So in summary, it’s important to remember that the regression line comes from computing expectations, and these give you two different lines, depending on if you compute the expectation of y given x or x given y.
[][Textbook link]
The link to the corresponding section of the textbook is warning: there are two regression lines. https://rafalab.github.io/dsbook/regression.html#warning-there-are-two-regression-lines
[][Key point] There are two different regression lines depending on whether we are taking the expectation of Y given X or taking the expectation of X given Y.
Code
# compute a regression line to predict the son's height from the father's height
mu_x <- mean(galton_heights$father)
mu_y <- mean(galton_heights$son)
s_x <- sd(galton_heights$father)
s_y <- sd(galton_heights$son)
r <- cor(galton_heights$father, galton_heights$son)
m_1 <- r * s_y / s_x
b_1 <- mu_y - m_1*mu_x
# compute a regression line to predict the father's height from the son's height
m_2 <- r * s_x / s_y
b_2 <- mu_x - m_2*mu_y
m_1
## [1] 0.5027904
b_1
## [1] 35.71249
m_2
## [1] 0.4986676
b_2
## [1] 33.96539
mu_x <- mean(galton_heights$father)
mu_y <- mean(galton_heights$son)
s_x <- sd(galton_heights$father)
x_y <- sd(galton_heights$son)
r <- cor(galton_heights$father, galton_heights$son)
m <- r * s_y/s_x # Thus the variance should be changed to variance**2, why made mistakes, poor Harvard
b <- mu_y - m*mu_x
m
## [1] 0.5027904
b
## [1] 35.71249
Song predict father wrong
compute expected value of x given y
m <- r * s_x/s_y
b <- mu_x - m*mu_y
m
## [1] 0.4986676
b
## [1] 33.96539
image here
two different lines depending on what you do
Look at the figure below. Scatter plot of son and father heights with
son heights on the y-axis and father heights on the x-axis. There is
also a regression line that runs from roughly (63,66) to (78,76). The
dots on the plot are scattered around the line. The slope of the
regression line in this figure is equal to what, in words? Slope
= (correlation coefficient of son and father heights) * (standard
deviation of sons’ heights / standard deviation of fathers’
heights) Slope = (correlation coefficient of son and father
heights) * (standard deviation of fathers’ heights / standard deviation
of sons’ heights) Slope = (correlation coefficient of son and father
heights) / (standard deviation of sons’ heights * standard deviation of
fathers’ heights) Slope = (mean height of fathers) - (correlation
coefficient of son and father heights * mean height of sons).
1 point possible (graded) Why does the regression line simplify to a line with intercept zero and slope rho when we standardize our x and y variables?
Try the simplification on your own first! When we standardize variables, both x and y will have a mean of one and a standard deviation of zero. When you substitute this into the formula for the regression line, the terms cancel out until we have the following equation: y_i = rho * x_i. When we standardize variables, both x and y will have a mean of zero and a standard deviation of one. When you substitute this into the formula for the regression line, the terms cancel out until we have the following equation: y_i = rho * x_i. When we standardize variables, both x and y will have a mean of zero and a standard deviation of one. When you substitute this into the formula for the regression line, the terms cancel out until we have the following equation: y_i = rho + x_i.
1 point possible (graded) What is a limitation of calculating conditional means?
Select ALL that apply. Each stratum we condition on (e.g., a specific father’s height) may not have many data points. Because there are limited data points for each stratum, our average values have large standard errors. Conditional means are less stable than a regression line. Conditional means are a useful theoretical tool but cannot be calculated.
1/1 point (graded) A regression line is the best prediction of Y given we know the value of X when: X and Y follow a bivariate normal distribution. Both X and Y are normally distributed. Both X and Y have been standardized. There are at least 25 X-Y pairs.
0/1 point (graded) Which one of the following scatterplots depicts an x and y distribution that is NOT well-approximated by the bivariate normal distribution?
I chose 3, but false, why.
The v-shaped distribution of points from the first plot means that the x and y variables do not follow a bivariate normal distribution.
****When a pair of random variables is approximated by a bivariate normal, the scatter plot looks like an oval**** (as in the 2nd, 3rd, and 4th plots) - [][it is okay if the oval is very round (as in the 3rd plot) or long and thin (as in the 4th plot)].
0/1 point (graded)
We previously calculated that the correlation coefficient between
fathers’ and sons’ heights is 0.5. Given this, what percent of the
variation in sons’ heights is explained by fathers’ heights? 0% 25%
50% 75% incorrect I choose 50% which is incorrect,
Think, Think, Think Answer Incorrect: Try again. [][When two variables
follow a bivariate normal distribution, the variation explained can be
calculated as rho^2 x
100](How does this comes from???).
1/1 point (graded)
Suppose the correlation between father and son’s height is 0.5, the standard deviation of fathers’ heights is 2 inches, and the standard deviation of sons’ heights is 3 inches. Given a one inch increase in a father’s height, what is the predicted change in the son’s height? 0.333 0.5 0.667 0.75 1 1.5 correct Answer Correct: Correct! TThe slope of the regression line is calculated by multiplying the correlation coefficient by the ratio of the standard deviation of son heights and standard deviation of father heights: var_son/var_father. (Note: here he means SD_son/SD_father, its a mistake) .
Comprehension Check due May 29, 2022 00:29 AWST
In the second part of this assessment, you’ll analyze a set of mother and daughter heights, also from GaltonFamilies.
Define female_heights, a set of mother and daughter heights sampled from GaltonFamilies, as follows:
set.seed(1989) #if you are using R 3.5 or earlier set.seed(1989, sample.kind=“Rounding”) #if you are using R 3.6 or later library(HistData) data(“GaltonFamilies”)
female_heights <- GaltonFamilies%>%
filter(gender == “female”) %>%
group_by(family) %>%
sample_n(1) %>%
ungroup() %>%
select(mother, childHeight) %>%
rename(daughter = childHeight)
set.seed(1989, sample.kind="Rounding") #if you are using R 3.6 or later
## Warning in set.seed(1989, sample.kind = "Rounding"): non-uniform 'Rounding'
## sampler used
library(HistData)
data("GaltonFamilies")
female_heights <- GaltonFamilies %>%
filter(gender == "female") %>%
group_by(family) %>%
sample_n(1) %>%
ungroup() %>%
select(mother, childHeight) %>%
rename(daughter = childHeight)
mean(female_heights$mother)
## [1] 64.125
sd(female_heights$mother)
## [1] 2.289292
mean(female_heights$daughter)
## [1] 64.28011
sd(female_heights$daughter)
## [1] 2.39416
cor(female_heights$mother, female_heights$daughter)
## [1] 0.3245199
mu_x <- mean(female_heights$mother)
mu_y <- mean(female_heights$daughter)
s_x <- sd(female_heights$mother)
s_y <- sd(female_heights$daughter)
r <- cor(female_heights$mother, female_heights$daughter)
m <- r * s_y/s_x
b <- mu_y - m*mu_x
m
## [1] 0.3393856
b
## [1] 42.51701
m*m
## [1] 0.1151826
outcome <- m * 60 + b
outcome
## [1] 62.88015
***Recall what we did in above courses***
mu_x <- mean(galton_heights$father)
mu_y <- mean(galton_heights$son)
s_x <- sd(galton_heights$father)
x_y <- sd(galton_heights$son)
r <- cor(galton_heights$father, galton_heights$son)
m <- r * s_y/s_x # Thus the variance should be changed to variance**2, why made mistakes, poor Harvard
b <- mu_y - m*mu_x
5/5 points (graded)
Calculate the mean and standard deviation of mothers’ heights, the mean and standard deviation of daughters’ heights, and the correlaton coefficient between mother and daughter heights. Mean of mothers’ heights correct 64.125
Loading Standard deviation of mothers’ heights correct 2.289292
Loading Mean of daughters’ heights correct 64.28011
Loading Standard deviation of daughters’ heights correct 2.39416
Loading Correlation coefficient correct 0.3245199
Loading You have used 1 of 10 attempts Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button. Correct (5/5 points)
3/3 points (graded)
Calculate the slope and intercept of the regression line predicting daughters’ heights given mothers’ heights. Given an increase in mother’s height by 1 inch, how many inches is the daughter’s height expected to change? Slope of regression line predicting daughters’ height from mothers’ heights correct 0.3393856
Loading Intercept of regression line predicting daughters’ height from mothers’ heights correct 42.51701
Loading Change in daughter’s height in inches given a 1 inch increase in the mother’s height correct 0.3393856
Loading You have used 1 of 10 attempts Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button. Correct (3/3 points)
1/1 point (graded) What percent of the variability in daughter heights is explained by the mother’s height?
Report your answer as a value between 0 and 100. Do NOT include the percent symbol (%) in your submission. correct 11
Loading You have used 4 of 10 attempts Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button. Correct (1/1 point)
1/1 point (graded)
A mother has a height of 60 inches. Using the regression formula, what is the conditional expected value of her daughter’s height given the mother’s height? correct 62.88015
Loading You have used 1 of 10 attempts Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button. Correct (1/1 point)
Ask your questions or make your comments about Stratification and Variance Explained here! Remember, one of the best ways to reinforce your own learning is by explaining something to someone else, so we encourage you to answer each other’s questions (without giving away the answers, of course).
Some reminders:
Search the discussion board before posting to see if someone else has asked the same thing before asking a new question
Please be specific in the title and body of your post regarding which question you're asking about to facilitate answering your question.
Posting snippets of code is okay, but posting full code solutions is not.
If you do post snippets of code, please format it as code for readability. If you're not sure how to do this, there are instructions in a pinned post in the "general" discussion forum.
In the Linear Models section, you will learn how to do linear regression.
After completing this section, you will be able to:
Use multivariate regression to adjust for confounders.
Write linear models to describe the relationship between two or more variables.
Calculate the least squares estimates for a regression model using the lm function.
Understand the differences between tibbles and data frames.
Use the do() function to bridge R functions and the tidyverse.
Use the tidy(), glance(), and augment() functions from the broom package.
Apply linear regression to measurement error models.
This section has four parts: Introduction to Linear Models, Least Squares Estimates, Tibbles, do, and broom, and Regression and Baseball. There are comprehension checks at the end of each part, along with an assessment on linear models at the end of the whole section for Verified learners only.
We encourage you to use R to interactively test out your answers and further your own learning. If you get stuck, we encourage you to search the discussion boards for the answer to your issue or ask us for help!
In a previous video, we found that the slope of the regression line
for predicting runs from bases on balls was 0.735. So, does this
mean that if we go and hire low salary players with many bases on balls
that increases the number of walks per game by 2 for our team? Our team
will score 1.47 more runs per game? [][We are again reminded
that association is not causation]. The data does provide strong
evidence that a team with 2 more bases on balls per game than the
average team scores 1.47 more runs per game, but this does not mean that
bases on balls are the cause. If we do compute the regression line slope
for singles, we get 0.449, a lower value. Note that a single gets you to
first base just like a base on balls. Those that know a little bit more
about baseball will tell you that with a single, runners that are on
base have a better chance of scoring than with a base on balls
(DId you see the logic conflict here).
So, how can base on balls be more predictive of runs? The reason this happens is because of [][confounding]. Note the correlation between homeruns, bases on balls, and singles. We see that the correlation between bases on balls and homeruns is quite high compared to the other two pairs. [][It turns out that pitchers, afraid of homeruns, will sometimes avoid throwing strikes to homerun hitters]. As a result, homerun hitters tend to have more bases on balls. Thus, a team with many homeruns will also have more bases on balls than average, and as a result, it may appear that bases on balls cause runs. But it is actually the homeruns that caused the runs.
In this case, we say that bases on balls are confounded with homeruns. [][But could it be that bases on balls still help? To find out, we somehow have to adjust for the homerun effect. Regression can help with this]. =============================================================================================================================
library(Lahman)
library(tidyverse)
#library(dslabs)
Teams %>%
filter(yearID %in% 1961:2001) %>%
mutate(Singles = (H - HR - X2B - X3B)/G, BB = BB/G, HR = HR/G) %>%
summarize(cor(BB, HR), cor(Singles, HR), cor(BB, Singles))
## cor(BB, HR) cor(Singles, HR) cor(BB, Singles)
## 1 0.4039313 -0.1737435 -0.05603822
[][Did you see the logic conflict here ??? Single-R slope
< BB-R slope, but Single gives runner better chance. Now
interesting]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
To try to determine if bases on balls is still useful for creating runs, a first approach is to keep home runs fixed at a certain value and then examine the relationship between runs and bases on balls. As we did when we stratified fathers by rounding to the closest inch, here, we can stratify home runs per game to the closest 10th. [][We filtered our strata with few points. We use this code to generate an informative data set. And then, we can make a scatter plot for each strata]. A scatterplot of runs versus bases on balls. This is what it looks like. Remember that the regression slope for predicting runs with bases on balls when we ignore home runs was 0.735.
[][But once we stratify by home runs, these slopes are substantially reduced]. We can actually see what the slopes are by using this code. We stratify by home run and then compute the slope using the formula that we showed you previously. These values are closer to the slope we obtained from singles, which is 0.449. Which is more consistent with our intuition. Since both singles and bases on ball get us to first base, they should have about the same predictive power.
Now, although our understanding of the application– our understanding of baseball–tells us that home runs cause bases on balls and not the other way around, we can still check if, after stratifying by base on balls, we still see a home run effect or if it goes down. We use the same code that we just used for bases on balls. But now, we swap home runs for bases on balls to get this plot. In this case, the slopes are the following. You can see they are all around 1.5, 1.6, 1.7. So they do not change that much from the original slope estimate, which was 1.84.
[][Regardless, it seems that if we stratify by home runs, we have an approximately bivariate normal distribution for runs versus bases on balls. Similarly, if we stratify by bases on balls, we have an approximately normal bivariate distribution for runs versus home runs. So what do we do?] It is somewhat complex to be computing regression lines for each strata. We’re essentially fitting this model that you can see in this equation with the slopes for x1 changing for different values of x2 and vice versa. Here, x1 is bases on balls. And x2 are home runs. Is there an easier approach? (So we have to take whole influence aerospace into a equation???)
[][Note that if we take random variability into account, the
estimated slopes by strata don’t appear to change that much]
(Sorry what ???). If these slopes are in fact the
same, this implies that this function beta 1 of x2 and the other
function beta 2 of x1 are actually constant. Which, in turn,
implies that the expectation of runs condition on home runs and bases on
balls can be written in this simpler model. This model implies that if
the number of home runs is fixed, we observe a linear relationship
between runs and bases on balls. And that the slope of that relationship
does not depend on the number of home runs. Only the slope changes as
the home runs increase. (Someone asked a question here)
[][The statement “Only the slope changes as the home runs increase”
is actually incorrect. We have since modified the script and re-filmed
the video, though editing for the updated video has not been completed
yet. The correct, updated text will be “Only the INTERCEPT changes”. I
will add a comment on the video page now until the updated video is
uploaded.] Thingking and asking and answering.
[][The same is true if we swap home runs and bases on balls. In this analysis, referred to as multivariate regression, we say that the bases on balls slope beta 1 is adjusted for the home run effect. If this model is correct, then confounding has been accounted for. But how do we estimate beta 1 and beta 2 from the data? For this, we’ll learn about linear models and least squares estimates.]
[][Textbook link]
This video corresponds to the textbook section on multivariate regression. https://rafalab.github.io/dsbook/linear-models.html#multivariate-regression
[][Key points]
A first approach to check confounding is to keep HRs fixed at a certain value and then examine the relationship between BB and runs.
The slopes of BB after stratifying on HR are reduced, but they are not 0, which indicates that BB are helpful for producing runs, just not as much as previously thought.
NOTE: There is an error in the script. The quote "Only the slope changes as the home runs increase." will be corrected to "Only the INTERCEPT changes as the home runs increase." in a future version of the video.
Code
# stratify HR per game to nearest 10, filter out strata with few points
dat <- Teams %>% filter(yearID %in% 1961:2001) %>%
mutate(HR_strata = round(HR/G, 1),
BB_per_game = BB / G,
R_per_game = R / G) %>%
filter(HR_strata >= 0.4 & HR_strata <=1.2)
# scatterplot for each HR stratum
dat %>%
ggplot(aes(BB_per_game, R_per_game)) +
geom_point(alpha = 0.5) +
geom_smooth(method = "lm") +
facet_wrap( ~ HR_strata)
## `geom_smooth()` using formula 'y ~ x'
# calculate slope of regression line after stratifying by HR
dat %>%
group_by(HR_strata) %>%
summarize(slope = cor(BB_per_game, R_per_game)*sd(R_per_game)/sd(BB_per_game))
## # A tibble: 9 x 2
## HR_strata slope
## <dbl> <dbl>
## 1 0.4 0.734
## 2 0.5 0.566
## 3 0.6 0.412
## 4 0.7 0.285
## 5 0.8 0.365
## 6 0.9 0.261
## 7 1 0.512
## 8 1.1 0.454
## 9 1.2 0.440
# stratify by BB
dat <- Teams %>% filter(yearID %in% 1961:2001) %>%
mutate(BB_strata = round(BB/G, 1),
HR_per_game = HR / G,
R_per_game = R / G) %>%
filter(BB_strata >= 2.8 & BB_strata <=3.9)
# scatterplot for each BB stratum
dat %>% ggplot(aes(HR_per_game, R_per_game)) +
geom_point(alpha = 0.5) +
geom_smooth(method = "lm") +
facet_wrap( ~ BB_strata)
## `geom_smooth()` using formula 'y ~ x'
# slope of regression line after stratifying by BB
dat %>%
group_by(BB_strata) %>%
summarize(slope = cor(HR_per_game, R_per_game)*sd(R_per_game)/sd(HR_per_game))
## # A tibble: 12 x 2
## BB_strata slope
## <dbl> <dbl>
## 1 2.8 1.52
## 2 2.9 1.57
## 3 3 1.52
## 4 3.1 1.49
## 5 3.2 1.58
## 6 3.3 1.56
## 7 3.4 1.48
## 8 3.5 1.63
## 9 3.6 1.83
## 10 3.7 1.45
## 11 3.8 1.70
## 12 3.9 1.30
dat <- Teams %>%
filter(yearID %in% 1961:2001) %>%
mutate(HR_strata = round(HR/G, 1),
BB_per_game = BB/G,
R_per_game = R/G) %>%
filter(HR_strata >= 0.4 & HR_strata <= 1.2)
head(dat)
## yearID lgID teamID franchID divID Rank G Ghome W L DivWin WCWin LgWin
## 1 1961 AL BAL BAL <NA> 3 163 82 95 67 <NA> <NA> N
## 2 1961 AL BOS BOS <NA> 6 163 82 76 86 <NA> <NA> N
## 3 1961 AL CHA CHW <NA> 4 163 81 86 76 <NA> <NA> N
## 4 1961 NL CHN CHC <NA> 7 156 78 64 90 <NA> <NA> N
## 5 1961 NL CIN CIN <NA> 1 154 77 93 61 <NA> <NA> Y
## 6 1961 AL CLE CLE <NA> 5 161 81 78 83 <NA> <NA> N
## WSWin R AB H X2B X3B HR BB SO SB CS HBP SF RA ER ERA CG SHO SV
## 1 N 691 5481 1393 227 36 149 581 902 39 30 NA NA 588 526 3.22 54 21 33
## 2 N 729 5508 1401 251 37 112 647 847 56 36 NA NA 792 687 4.29 35 6 30
## 3 N 765 5556 1475 216 46 138 550 612 100 40 NA NA 726 653 4.06 39 3 33
## 4 N 689 5344 1364 238 51 176 539 1027 35 25 NA NA 800 689 4.48 34 6 25
## 5 N 710 5243 1414 247 35 158 423 761 70 33 NA NA 653 575 3.78 46 12 40
## 6 N 737 5609 1493 257 39 150 492 720 34 11 NA NA 752 665 4.15 35 12 23
## IPouts HA HRA BBA SOA E DP FP name park
## 1 4413 1226 109 617 926 126 173 0.980 Baltimore Orioles Memorial Stadium
## 2 4326 1472 167 679 831 143 140 0.977 Boston Red Sox Fenway Park II
## 3 4344 1491 158 498 814 128 138 0.980 Chicago White Sox Comiskey Park
## 4 4155 1492 165 465 755 183 175 0.970 Chicago Cubs Wrigley Field
## 5 4110 1300 147 500 829 134 124 0.977 Cincinnati Reds Crosley Field
## 6 4329 1426 178 599 801 139 142 0.977 Cleveland Indians Cleveland Stadium
## attendance BPF PPF teamIDBR teamIDlahman45 teamIDretro HR_strata BB_per_game
## 1 951089 96 96 BAL BAL BAL 0.9 3.564417
## 2 850589 102 103 BOS BOS BOS 0.7 3.969325
## 3 1146019 99 97 CHW CHA CHA 0.8 3.374233
## 4 673057 101 104 CHC CHN CHN 1.1 3.455128
## 5 1117603 102 101 CIN CIN CIN 1.0 2.746753
## 6 725547 97 98 CLE CLE CLE 0.9 3.055901
## R_per_game
## 1 4.239264
## 2 4.472393
## 3 4.693252
## 4 4.416667
## 5 4.610390
## 6 4.577640
dat %>%
ggplot2::ggplot(aes(BB_per_game, R_per_game)) +
geom_point(alpha=0.3) +
geom_smooth(formula = y ~ x, method = "lm") +
facet_wrap(~HR_strata)
dat %>%
group_by(HR_strata) %>%
summarise(slope = cor(BB_per_game, R_per_game) * sd(R_per_game) / sd(BB_per_game))
## # A tibble: 9 x 2
## HR_strata slope
## <dbl> <dbl>
## 1 0.4 0.734
## 2 0.5 0.566
## 3 0.6 0.412
## 4 0.7 0.285
## 5 0.8 0.365
## 6 0.9 0.261
## 7 1 0.512
## 8 1.1 0.454
## 9 1.2 0.440
dat <- Teams %>%
filter(yearID %in% 1961:2001) %>%
mutate(BB_strata = round(BB/G, 1),
HR_per_game = HR/G,
R_per_game = R/G) %>%
filter(BB_strata >= 2.8 & BB_strata <= 3.9)
dat %>%
ggplot(aes(HR_per_game, R_per_game)) +
geom_point(alpha=0.3) +
geom_smooth(formula = y~x, method = "lm") +
facet_wrap(~BB_strata)
dat %>%
group_by(BB_strata) %>%
summarise(slope = cor(HR_per_game, R_per_game) * sd(R_per_game) / sd(HR_per_game))
## # A tibble: 12 x 2
## BB_strata slope
## <dbl> <dbl>
## 1 2.8 1.52
## 2 2.9 1.57
## 3 3 1.52
## 4 3.1 1.49
## 5 3.2 1.58
## 6 3.3 1.56
## 7 3.4 1.48
## 8 3.5 1.63
## 9 3.6 1.83
## 10 3.7 1.45
## 11 3.8 1.70
## 12 3.9 1.30
Since Galton’s original development, regression has become
one of the most widely used tools in data science. One reason
for this has to do with the fact that [][regression permits us to
find relationships between two variables while adjusting for
others], as we have just shown for bases on balls and home runs.
This has been particularly popular in fields where randomized
experiments are hard to run
(Think, other cases ? can we apply it into analyzing app users ???),
such as economics and epidemiology. When we’re not able to
randomly assign each individual to a treatment or control group,
confounding is particularly prevalent.
For example, consider estimating the effect of any fast foods on life
expectancy using data collected from a random sample of people in some
jurisdiction. Fast food consumers are more likely to be smokers,
drinkers, and have lower incomes
(Your customer groups are already limited into certain group).
Therefore, a naive regression model may lead to an overestimate of a
negative health effect of fast foods. So how do we adjust for
confounding in practice? We can use regression. [][We have described
how, if data is bivariate normal, then the conditional expectation
follow a regression line], that the conditional expectation as a
line is not an extra assumption, but rather a result derived from the
assumption, that they are approximately bivariate normal.
[][However, in practice it is common to explicitly write down a model that describes the relationship between two or more variables using what is called a linear model]. We know that linear here does not refer to lines exclusively, but rather to the fact that the conditional expectation is a linear combination of known quantities. Any combination that multiplies them by a constant and then adds them up with, perhaps, a shift. For example, 2 plus 3x minus 4y plus 5z is a linear combination of x, y, and z. So beta 0 plus beta 1x1, plus beta 2x 2 is a linear combination of x1 and x2. The simplest linear model is a constant beta 0. The second simplest is a line, beta 0 plus beta 1x.
For Galton’s data, we would denote n observed fathers’ heights with x1 through xn. Then we model n son heights we are trying to predict with the following model. Here, the little xi’s are the father’s heights, which are fixed not random, due to the conditioning. We’ve conditioned on these values. And then Yi big Yi is the random son’s height that we want to predict. We further assume that the errors that are denoted with the Greek letter for E, epsilon, epsilon i, are independent from each other, have expected value 0, and the standard deviation, which is usually called sigma, does not depend on i. It’s the same for every individual. We know the xi, but [][to have a useful model for prediction, we need beta 0 and beta 1. We estimate these from the data]. Once we do, we can predict the sons’ heights from any father’s height, x. Note that if we further assume that the epsilons are normally distributed, then this model is exactly the same one we derived earlier for the bivariate normal distribution. A somewhat nuanced difference is that in the first approach, we assumed the data was a bivariate normal, and [][the linear model was derived, not assumed].
In practice, linear models are just assumed without necessarily assuming normality. The distribution of the epsilons is not specified. But nevertheless, if your data is bivariate normal, the linear model that we just showed holds. If your data is not bivariate normal, then you will need to have other ways of justifying the model ([][Here, what is the other way to justifying the models ???]). One reason linear models are popular is that they are interpretable. In the case of Galton’s data, we can interpret the data like this. Due to inherited genes, the son’s height prediction grows by beta 1 for each inch we increase the father’s height x. Because not all sons with fathers of height x are of equal height, we need the term epsilon, which explains the remaining variability. This remaining variability includes the mother’s genetic effect, environmental factors, and other biological randomness.
Note that given how we wrote the model, the intercept beta 0 is not very interpretable, as it is the predicted height of a son with a father with no height. Due to regression to the mean, the prediction will usually be a bit larger than 0, which is really not very interpretable. To make the intercept parameter more interpretable, we can rewrite the model slightly in the following way. Here, we have changed xi to xi minus the average height x bar. We have centered our covariate xi. In this case, beta 0, the intercept, would be the predicted height for the average father for the case where xi equals x bar.
quotation form the book: Note that if we further assume that the ε is normally distributed, then this model is exactly the same one we derived earlier by assuming bivariate normal data. A somewhat nuanced difference is that in the first approach we assumed the data was bivariate normal and that the linear model was derived, not assumed. In practice, linear models are just assumed without necessarily assuming normality: the distribution of the εs is not specified. Nevertheless, if your data is bivariate normal, the above linear model holds. If your data is not bivariate normal, then you will need to have other ways of justifying the model.
[][Textbook link]
This video corresponds to the textbook section on linear models. https://rafalab.github.io/dsbook/linear-models.html
[][Key points]
“Linear” here does not refer to lines, but rather to the fact that the conditional expectation is a linear combination of known quantities.
[][* In Galton’s model, we assume Y (son’s height) is a linear combination of a constant and X (father’s height) plus random noise. We further assume that Epsilon_i are independent from each other, have expected value 0 and the standard deviation Sigma which does not depend on i.*] Note that if we further assume that Epsilon is normally distributed, then the model is exactly the same one we derived earlier by assuming bivariate normal data. We can subtract the mean from X to make more Beta_0 interpretable.
linear combination of x, y and z
a horizontal line
second simplest linear mode have a slopel
random son heights we want to predict with conditioned fathers heights.png
In father-son heights dataset
So smart
1/1 point (graded) As described in the videos, when we stratified our regression lines for runs per game vs. bases on balls by the number of home runs, what happened? The slope of runs per game vs. bases on balls within each stratum was reduced because we removed confounding by home runs. The slope of runs per game vs. bases on balls within each stratum was reduced because there were fewer data points. The slope of runs per game vs. bases on balls within each stratum increased after we removed confounding by home runs. The slope of runs per game vs. bases on balls within each stratum stayed about the same as the original slope. correct Answer Correct: Correct.
1/1 point (graded)
We run a linear model for sons’ heights vs. fathers’ heights using the Galton height data, and get the following results:
> lm(son ~ father, data = galton_heights)
Call: lm(formula = son ~ father, data = galton_heights)
Coefficients: (Intercept) father
35.71 0.50
Interpret the numeric coefficient for “father.” For every inch we increase the son’s height, the predicted father’s height increases by 0.5 inches. For every inch we increase the father’s height, the predicted son’s height grows by 0.5 inches. For every inch we increase the father’s height, the predicted son’s height is 0.5 times greater. correct
Explanation
The coefficient for “father” gives the predicted increase in son’s height for each increase of 1 unit in the father’s height. In this case, it means that for every inch we increase the father’s height, the son’s predicted height increases by 0.5 inches.
1/1 point (graded)
We want the intercept term for our model to be more interpretable, so we run the same model as before but now we subtract the mean of fathers’ heights from each individual father’s height to create a new variable centered at zero.
galton_heights <- galton_heights %>%
mutate(father_centered=father - mean(father))
We run a linear model using this centered fathers’ height variable.
> lm(son ~ father_centered, data = galton_heights)
Call: lm(formula = son ~ father_centered, data = galton_heights)
Coefficients: (Intercept) father_centered
70.45 0.50
Interpret the numeric coefficient for the intercept. The height of a son of a father of average height is 70.45 inches. The height of a son when a father’s height is zero is 70.45 inches. The height of an average father is 70.45 inches. correct
Explanation
Because the fathers’ heights (the independent variable) have been centered on their mean, the intercept represents the height of the son of a father of average height. In this case, that means that the height of a son of a father of average height is 70.45 inches.
If we had not centered fathers’ heights to its mean, then the intercept would represent the height of a son when a father’s height is zero.
1/1 point (graded)
Suppose we fit a multivariable regression model for expected runs based on BB and HR:
E[R|BB = x_1, HR = x_2] = Beta_0 + Beta_1 * x_1 + Beta_2 * x_2
Suppose we fix . Then we observe a linear relationship between runs and HR with intercept of:
Beta_0 Beta_0 + Beta_2 * x_2 Beta_0 + Beta_1 * x_1 Beta_0 + Beta_2 * x_1
correct
Explanation
If is fixed BB=x_1, then is fixed and acts as the intercept for this regression model. This is the basis of stratificaton.
0.67/1 point (graded) Which of the following are assumptions for the errors Epsilon in a linear regression model?
Check ALL correct answers. The Epsilon are independent of each other correct The Epsilon have expected value 0 correct The variance of Epsilon is a constant correct partially correct
lm(formula = son ~ father, data = galton_heights)
##
## Call:
## lm(formula = son ~ father, data = galton_heights)
##
## Coefficients:
## (Intercept) father
## 35.7125 0.5028
Summary: R linear regression uses the lm() function to create a regression model given some formula, in the form of Y~X+X2. To look at the model, you use the summary() function.
galton_heights <- galton_heights %>%
mutate(father_centered = father - mean(father))
lm(son ~ father_centered, data = galton_heights)
##
## Call:
## lm(formula = son ~ father_centered, data = galton_heights)
##
## Coefficients:
## (Intercept) father_centered
## 70.4547 0.5028
# So intercept changed, a lot, does that mean the median father and mean son are not match?
# Or someone is not normal distributed ???
Ask your questions or make your comments about Introduction to Linear Models here! Remember, one of the best ways to reinforce your own learning is by explaining something to someone else, so we encourage you to answer each other’s questions (without giving away the answers, of course).
Some reminders:
Search the discussion board before posting to see if someone else has asked the same thing before asking a new question
Please be specific in the title and body of your post regarding which question you're asking about to facilitate answering your question.
Posting snippets of code is okay, but posting full code solutions is not.
If you do post snippets of code, please format it as code for readability. If you're not sure how to do this, there are instructions in a pinned post in the "general" discussion forum.
For linear models to be useful, we have to estimate the unknown parameters, the betas. The standard approach in science is to find the values that minimize the distance of the fitted model to the data. To quantify, this we use the [][least squares equation]. For Galton’s data, we would write something like this. This quantity is called the [][Residual Sum of Squares, RSS]. Once we find the values that minimize the RSS, we call the values the Least Squares Estimate, LSE, and denote them, in this case, with beta 0 hat and beta 1 hat.
[][Let’s write the function that computes the RSS for any pair of values, beta 0 and beta 1, for our heights data. It would look like this. So for any pair of values, we get an RSS. So this is a three-dimensional plot with beta 1 and beta 2, and x and y and the RSS as a z. To find the minimum, you would have to look at this three-dimensional plot]. Here, we’re just going to make a two-dimensional version by keeping beta 0 fixed at 25. So it will be a function of the RSS as a function of beta 1. We can use this code to produce this plot. We can see a clear minimum for beta 1 at around 0.65. So you could see how we would pick the least squares estimates. However, this minimum is for beta 1 when beta 0 is fixed at 25. But we don’t know if that’s the minimum for beta 0. We don’t know if 25 comma 0.65 minimizes the equation across all pairs.
[][****We could use trial and error, but it’s really not going to
work here (Why and How). Instead we will use calculus.****]
We’ll take the partial derivatives, set them
equal to 0, and solve for beta 1 and beta 0. Of course, if we have many
parameters, these equations can get rather complex. But there are
functions in R that do these calculations for us. We will learn these
soon. To learn the mathematics behind this, you can consult the book on
linear models.
quotation form the book: In mathematics, when we multiply each variable by a constant and then add them together, we say we formed a linear combination of the variables. For example, 3x−4y+5z is a linear combination of x, y, and z. We can also add a constant so 2+3x−4y+5z is also linear combination of x, y, and z.
[][Textbook link]
This video corresponds to the textbook section on least squares estimates. https://rafalab.github.io/dsbook/linear-models.html#lse
[][Key points]
For regression, we aim to find the coefficient values that minimize the distance of the fitted model to the data.
Residual sum of squares (RSS) measures the distance between the true value and the predicted value given by the regression line. The values that minimize the RSS are called the least squares estimates (LSE).
We can use partial derivatives to get the values for and in Galton's data.
NOTE: At timepoint 0:57 in the video, the Professor uses the terms and , but this should be and
Code
library(HistData)
library(tidyverse)
data("GaltonFamilies")
set.seed(1983)
galton_heights <- GaltonFamilies %>%
filter(gender == "male") %>%
group_by(family) %>%
sample_n(1) %>%
ungroup() %>%
select(father, childHeight) %>%
rename(son = childHeight)
#https://bookdown.org/yih_huynh/Guide-to-R-Book/groupby.html
rss <- function(beta0, beta1){
resid <- galton_heights$son - (beta0 + beta1 * galton_heights$father)
return(sum(resid^2))
}
# plot RSS as a function of beta1 when beta0=25
beta1 = seq(0, 1, len=nrow(galton_heights))
results <- data.frame(beta1 = beta1,
rss = sapply(beta1, rss, beta0 = 25))
# https://r-lang.com/r-sapply/
results %>%
ggplot(aes(beta1, rss)) +
geom_line()
rss <- function(beta0, beta1, data){
resid <- galton_heights$son - (beta0 + beta1 * galton_heights$father)
return(sum(resid^2))
}
beta1 = seq(0, 1, len=nrow(galton_heights))
results <- data.frame(beta1 = beta1,
rss = sapply(beta1, rss, beta0 = 25))
results %>%
ggplot(aes(beta1, rss)) +
#geom_line() +
geom_line(aes(beta1, rss), col=2)
[][Definition of trial and error: a finding out of the best way to reach a desired result or a correct solution by trying out one or more ways or means and by noting and eliminating errors or causes of failure also : the trying of one thing or another until something succeeds.]
[][In r, we can obtain the least squares estimates using the lm function]. To fit the following model where Yi is the son’s height and Xi is the father height, we would write the following piece of code. This gives us the least squares estimates, which we can see in the output of r. The general way we use lm is by using the tilde (~) character to let lm know which is the value we’re predicting that’s on the left side of the tilde, and which variables we’re using to predict–those will be on the right side of the tilde. The intercept is added automatically to the model. So you don’t have to include it when you write it.
The object fit that we just computed includes more information about the least squares fit. We can use the function summary to extract more of this information, like this. To understand some of the information included in this summary, we need to remember that the LSE are random variables. Mathematical statistics gives us some ideas of the distribution of these random variables. And we’ll learn some of that next. End of transcript. Skip to the start.
[][Textbook link]
This video corresponds to the textbook section on the lm function. https://rafalab.github.io/dsbook/linear-models.html#the-lm-function
[][Key points]
When calling the lm() function, the variable that we want to predict is put to the left of the ~ symbol, and the variables that we use to predict is put to the right of the ~ symbol. The intercept is added automatically.
LSEs are random variables.
Code
library(HistData)
data("GaltonFamilies")
galton_heights <- GaltonFamilies %>%
filter(childNum == 1 & gender == 'male') %>%
select(father, childHeight) %>%
rename(son=childHeight)
# fit regression line to predict son's height from father's height
fit <- lm(son ~ father, data = galton_heights)
fit
##
## Call:
## lm(formula = son ~ father, data = galton_heights)
##
## Coefficients:
## (Intercept) father
## 35.7125 0.5028
# summary statistics
summary(fit)
##
## Call:
## lm(formula = son ~ father, data = galton_heights)
##
## Residuals:
## Min 1Q Median 3Q Max
## -5.9022 -1.4050 0.0922 1.3422 8.0922
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 35.71249 4.51737 7.906 2.75e-13 ***
## father 0.50279 0.06533 7.696 9.47e-13 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.22 on 177 degrees of freedom
## Multiple R-squared: 0.2507, Adjusted R-squared: 0.2465
## F-statistic: 59.23 on 1 and 177 DF, p-value: 9.473e-13
fit <- lm(son ~ father, data = galton_heights)
fit
##
## Call:
## lm(formula = son ~ father, data = galton_heights)
##
## Coefficients:
## (Intercept) father
## 35.7125 0.5028
summary(fit)
##
## Call:
## lm(formula = son ~ father, data = galton_heights)
##
## Residuals:
## Min 1Q Median 3Q Max
## -5.9022 -1.4050 0.0922 1.3422 8.0922
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 35.71249 4.51737 7.906 2.75e-13 ***
## father 0.50279 0.06533 7.696 9.47e-13 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.22 on 177 degrees of freedom
## Multiple R-squared: 0.2507, Adjusted R-squared: 0.2465
## F-statistic: 59.23 on 1 and 177 DF, p-value: 9.473e-13
[][The LSE are derived from the data, Y1 through Yn, which are random. This implies that our estimates are random variables]. To see this, we can run a Monte Carlo simulation in which we assume that the son and father height data that we have defines an entire population. And we’re going to take random samples of size 50 and compute the regression slope coefficient for each one. We write this code, which gives us several estimates of the regression slope. We can see the variability of the estimates by plotting their distribution. Here you can see the histograms of the estimated beta 0’s and the estimated beta 1’s. [][The reason these look normal is because the central limit theorem applies here as well. For large enough N, the least squares estimates will be approximately normal with expected value beta 0 and beta 1 respectively].
The standard errors are a bit complicated to compute, but mathematical theory does allow us to compute them, and they are included in the summary provided by the lm function. Here are the estimated standard errors for one of our simulated data sets. You could see them at the second column in the coefficients table. [][You can see that the standard errors estimates reported by the summary function are close to the standard errors that we obtain from our Monte Carlo simulation].
The summary function also reports t-statistics–this is the t value column–and p-value. This is the Pr bigger than absolute value of t column. [][The t-statistic] is not actually based on the central limit theorem, but rather on the assumption that [][the epsilons follow a normal distribution]. Under this assumption, mathematical theory tells us that the LSE divided by their standard error, which we can see here and here, follow a t distribution with N minus p degrees of freedom, with p the number of parameters in our model, which in this case is 2.
The 2p values are testing the null hypothesis that beta 0 is 0 and beta 1 is 0 respectively.
[Go read this book][**https://www.statisticshowto.com/probability-and-statistics/null-hypothesis/]
[][Note that as we described previously, for large enough
N, the central limit works, and the t distribution becomes almost the
same as a normal distribution. So if either you assume the errors are
normal and use the t distribution or if you assume that N is large
enough to use the central limit theorem, you can construct confidence
intervals for your parameters.]
(How to construct confidnece intervals for our parameters)
We know here that although we will not show examples in this video, hypothesis testing for regression models is very commonly used in, for example, epidemiology and economics, to make statements such as the effect of A and B was statistically significant after adjusting for X, Y, and Z. But it’s very important to note that several assumptions–we just described some of them–have to hold for these statements to hold. [][the effect of A and B was statistically significant after adjusting for X, Y, and Z]
[][Textbook link]
This video corresponds to the textbook section on LSE. https://rafalab.github.io/dsbook/linear-models.html#lse-are-random-variables
[]Key points]
Because they are derived from the samples, LSE are random variables.
Beat_0 and Beta_1 appear to be normally distributed because the central limit theorem plays a role.
The t-statistic depends on the assumption that follows a normal distribution.
Code
# Monte Carlo simulation ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
B <- 1000
N <- 50
lse <- replicate(B, {
sample_n(galton_heights, N, replace = TRUE) %>%
lm(son ~ father, data = .) %>%
.$coef
})
lse <- data.frame(beta_0 = lse[1,], beta_1 = lse[2,])
# Plot the distribution of beta_0 and beta_1
library(gridExtra)
##
## Attaching package: 'gridExtra'
## The following object is masked from 'package:dplyr':
##
## combine
p1 <- lse %>% ggplot(aes(beta_0)) + geom_histogram(bins = 15, color = "black")
p2 <- lse %>% ggplot(aes(beta_1)) + geom_histogram(binwidth = 0.05, color = "black")
grid.arrange(p1, p2, ncol = 2)
# summary statistics
sample_n(galton_heights, N, replace = TRUE) %>%
lm(son ~ father, data = .) %>%
summary %>%
.$coef
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 31.9641244 7.6317391 4.188315 1.194960e-04
## father 0.5513639 0.1100775 5.008871 7.821676e-06
lse %>% summarize(se_0 = sd(beta_0), se_1 = sd(beta_1))
## se_0 se_1
## 1 8.99551 0.1298399
B <- 1000
N <- 50
lse <- replicate(B, {
sample_n(galton_heights, N, replace = TRUE) %>%
lm(son ~ father, data = .) %>%
.$coef
})
lse <- data.frame(beta_0 = lse[1, ], beta_1 = lse[2, ])
head(lse)
## beta_0 beta_1
## 1 37.81318 0.4748176
## 2 31.44613 0.5604301
## 3 42.86975 0.4009377
## 4 23.15062 0.6898149
## 5 34.90689 0.5175281
## 6 42.93412 0.4008286
p1 <- lse %>% ggplot2::ggplot(aes(beta_0)) + geom_histogram(binwidth = 5, color = "black")
p2 <- lse %>% ggplot2::ggplot(aes(beta_1)) + geom_histogram(binwidth = 0.1, color = "black")
grid.arrange(p1, p2, ncol = 2)
sample_n(galton_heights, N, replace = TRUE) %>%
lm(son ~ father, data = .) %>%
summary
##
## Call:
## lm(formula = son ~ father, data = .)
##
## Residuals:
## Min 1Q Median 3Q Max
## -5.3600 -1.2751 0.2097 1.3369 5.0762
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 33.9137 7.1890 4.717 2.10e-05 ***
## father 0.5213 0.1043 4.996 8.17e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.026 on 48 degrees of freedom
## Multiple R-squared: 0.3421, Adjusted R-squared: 0.3284
## F-statistic: 24.96 on 1 and 48 DF, p-value: 8.171e-06
lse %>% summarise(se_0 = sd(beta_0), se_1 = sd(beta_1))
## se_0 se_1
## 1 9.058707 0.1306047
you can see the standard error estimates reported by the summary function are close to the standard errors that we obtained from our monte carlo simulation.png
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
hypothesis testing for regression models is very commonly used in many areas as the effecta and b was statistically significant after adjusting for x y and z.png
Although interpretation is not straight-forward, it is also useful to know that the LSE can be strongly correlated, which can be seen using this code:
lse %>% summarize(cor(beta_0, beta_1))
However, the correlation depends on how the predictors are defined or transformed.
Here we standardize the father heights, which changes x_i to x_i - x hat
.
B <- 1000 N <- 50 lse <- replicate(B, { sample_n(galton_heights, N, replace = TRUE) %>% mutate(father = father - mean(father)) %>% lm(son ~ father, data = .) %>% .$coef })
Observe what happens to the correlation in this case:
cor(lse[1,], lse[2,])
lse %>% summarize(cor(beta_0, beta_1))
## cor(beta_0, beta_1)
## 1 -0.9994401
B <- 1000
N <- 50
lse <- replicate(B, {
sample_n(galton_heights, N, replace = TRUE) %>%
mutate(father = father - mean(father)) %>%
lm(son ~ father, data = .) %>%
.$coef
})
cor(lse[1,], lse[2,])
## [1] -0.1781111
Once we fit our model, we can obtain predictions of y by
plugging the estimates (the Beta0 and Beta1 and etc.) into
the regression model. For example, if the father’s height is x,
then our prediction for y–which we’ll denote with a hat on top of the
y–for the son’s height will be the following. We’re just plugging in
beta–the estimated betas into the equation. If we plot y hat versus x,
we’ll see the regression line.
[][Note that the prediction y hat is also a random variable, and mathematical theory tells us what the standard errors are]. If we assume the errors are normal or have a large enough sample size to use the Central Limit Theorem, we can construct confidence intervals for our predictions, as well. In fact, the ggplot layer geom underscore smooth, when we set method equals to lm–we’ve previously shown this for several plots–plots confidence intervals around the predicted y hat. Let’s look at an example with this code. You can see the regression line. Those are the predictions, and you see a band around them. Those are the confidence intervals.
[][The R function predict() takes an lm object as input and returns these predictions]. We can see it here in this code which produces this plot, and if requested the standard errors and other information from which we can construct confidence intervals can be obtained from the predict function. You can see it by running this code.
[][You must go read the book, read this is absolately not enough, and you forget] https://rafalab.github.io/dsbook/linear-models.html#predicted-values-are-random-variables ********************************************************************************************************
[][Textbook link]
This video corresponds to the textbook section on predicted values. https://rafalab.github.io/dsbook/linear-models.html#predicted-values-are-random-variables
[][Key points]
The predicted value is often denoted as Y_hat (image you put `^` on top of `Y`), which is a random variable. Mathematical theory tells us what the standard error of the predicted value is.
The predict() function in R can give us predictions directly.
Code
# plot predictions and confidence intervals
galton_heights %>%
ggplot(aes(father, son)) +
geom_point() +
geom_smooth(formula = y ~ x, method = "lm")
# predict Y directly
fit <- galton_heights %>%
lm(son ~ father, data = .)
Y_hat <- predict(fit, se.fit = TRUE) # https://stats.stackexchange.com/questions/86624/se-of-fit-versus-se-of-prediction
Y_hat
## $fit
## 1 2 3 4 5 6 7 8
## 75.18154 73.67317 73.42177 73.42177 73.42177 72.91898 72.91898 72.41619
## 9 10 11 12 13 14 15 16
## 72.41619 72.41619 72.41619 72.41619 72.26536 71.91340 71.91340 71.91340
## 17 18 19 20 21 22 23 24
## 71.91340 71.91340 71.91340 72.16480 71.91340 71.91340 71.41061 71.41061
## 25 26 27 28 29 30 31 32
## 71.41061 71.41061 71.41061 71.41061 71.76257 71.41061 71.66201 71.66201
## 33 34 35 36 37 38 39 40
## 71.41061 71.76257 71.41061 71.66201 71.41061 71.41061 71.41061 71.41061
## 41 42 43 44 45 46 47 48
## 71.41061 71.41061 71.41061 71.41061 71.41061 70.90782 70.90782 70.90782
## 49 50 51 52 53 54 55 56
## 70.90782 70.90782 71.15922 70.90782 70.90782 70.90782 70.90782 70.90782
## 57 58 59 60 61 62 63 64
## 70.90782 70.90782 70.90782 70.90782 70.90782 71.15922 70.90782 70.90782
## 65 66 67 68 69 70 71 72
## 70.90782 71.15922 71.15922 70.90782 70.90782 70.90782 71.15922 71.05866
## 73 74 75 76 77 78 79 80
## 71.15922 70.90782 70.90782 70.90782 70.90782 70.40503 70.40503 70.40503
## 81 82 83 84 85 86 87 88
## 70.40503 70.40503 70.40503 70.65643 70.40503 70.65643 70.40503 70.40503
## 89 90 91 92 93 94 95 96
## 70.65643 70.50559 70.40503 70.40503 70.40503 70.40503 70.40503 70.65643
## 97 98 99 100 101 102 103 104
## 70.40503 70.65643 70.40503 70.40503 70.65643 70.40503 70.40503 70.40503
## 105 106 107 108 109 110 111 112
## 70.40503 70.25419 70.15364 70.15364 69.90224 69.90224 69.90224 69.90224
## 113 114 115 116 117 118 119 120
## 70.15364 70.15364 69.90224 69.90224 69.90224 69.90224 69.90224 70.15364
## 121 122 123 124 125 126 127 128
## 69.90224 69.90224 69.90224 69.90224 70.15364 69.90224 70.00280 69.90224
## 129 130 131 132 133 134 135 136
## 70.25419 69.90224 69.90224 69.90224 69.90224 69.90224 70.15364 69.90224
## 137 138 139 140 141 142 143 144
## 69.39945 69.39945 69.39945 69.39945 69.39945 69.39945 69.39945 69.65085
## 145 146 147 148 149 150 151 152
## 69.39945 69.39945 69.39945 69.65085 69.39945 68.89666 68.89666 68.89666
## 153 154 155 156 157 158 159 160
## 68.89666 69.14806 68.89666 68.89666 69.14806 69.14806 68.89666 68.89666
## 161 162 163 164 165 166 167 168
## 68.89666 68.89666 68.39387 68.39387 68.39387 68.39387 68.39387 68.39387
## 169 170 171 172 173 174 175 176
## 68.39387 68.39387 68.39387 68.64526 68.64526 67.89108 67.89108 67.89108
## 177 178 179
## 67.89108 66.88550 67.13689
##
## $se.fit
## [1] 0.6362006 0.4499005 0.4197098 0.4197098 0.4197098 0.3606249 0.3606249
## [8] 0.3041064 0.3041064 0.3041064 0.3041064 0.3041064 0.2878792 0.2518878
## [15] 0.2518878 0.2518878 0.2518878 0.2518878 0.2518878 0.2773032 0.2518878
## [22] 0.2518878 0.2072453 0.2072453 0.2072453 0.2072453 0.2072453 0.2072453
## [29] 0.2374913 0.2072453 0.2283243 0.2283243 0.2072453 0.2374913 0.2072453
## [36] 0.2283243 0.2072453 0.2072453 0.2072453 0.2072453 0.2072453 0.2072453
## [43] 0.2072453 0.2072453 0.2072453 0.1760402 0.1760402 0.1760402 0.1760402
## [50] 0.1760402 0.1894818 0.1760402 0.1760402 0.1760402 0.1760402 0.1760402
## [57] 0.1760402 0.1760402 0.1760402 0.1760402 0.1760402 0.1894818 0.1760402
## [64] 0.1760402 0.1760402 0.1894818 0.1894818 0.1760402 0.1760402 0.1760402
## [71] 0.1894818 0.1835265 0.1894818 0.1760402 0.1760402 0.1760402 0.1760402
## [78] 0.1660303 0.1660303 0.1660303 0.1660303 0.1660303 0.1660303 0.1679615
## [85] 0.1660303 0.1679615 0.1660303 0.1660303 0.1679615 0.1660361 0.1660303
## [92] 0.1660303 0.1660303 0.1660303 0.1660303 0.1679615 0.1660303 0.1679615
## [99] 0.1660303 0.1660303 0.1679615 0.1660303 0.1660303 0.1660303 0.1660303
## [106] 0.1679388 0.1704558 0.1704558 0.1807716 0.1807716 0.1807716 0.1807716
## [113] 0.1704558 0.1704558 0.1807716 0.1807716 0.1807716 0.1807716 0.1807716
## [120] 0.1704558 0.1807716 0.1807716 0.1807716 0.1807716 0.1704558 0.1807716
## [127] 0.1759914 0.1807716 0.1679388 0.1807716 0.1807716 0.1807716 0.1807716
## [134] 0.1807716 0.1704558 0.1807716 0.2152371 0.2152371 0.2152371 0.2152371
## [141] 0.2152371 0.2152371 0.2152371 0.1960501 0.2152371 0.2152371 0.2152371
## [148] 0.1960501 0.2152371 0.2617481 0.2617481 0.2617481 0.2617481 0.2373868
## [155] 0.2617481 0.2617481 0.2373868 0.2373868 0.2617481 0.2617481 0.2617481
## [162] 0.2617481 0.3150135 0.3150135 0.3150135 0.3150135 0.3150135 0.3150135
## [169] 0.3150135 0.3150135 0.3150135 0.2877599 0.2877599 0.3721442 0.3721442
## [176] 0.3721442 0.3721442 0.4925607 0.4619348
##
## $df
## [1] 177
##
## $residual.scale
## [1] 2.219652
names(Y_hat)
## [1] "fit" "se.fit" "df" "residual.scale"
# plot best fit line
galton_heights %>%
mutate(Y_hat = predict(lm(son ~ father, data=.))) %>%
ggplot(aes(father, Y_hat))+
geom_line()
galton_heights %>%
ggplot(aes(son, father)) +
geom_point() +
geom_smooth(formula= y ~ x, method="lm")
galton_heights %>%
mutate(Y_hat = predict(lm(formula = son ~ father, data = .))) %>%
ggplot(aes(father, Y_hat)) +
geom_line()
galton_heights_hat <- galton_heights %>%
mutate(Y_hat = predict(lm(son ~ father, data=.)))
head(galton_heights_hat)
## father son Y_hat
## 1 78.5 73.2 75.18154
## 2 75.5 73.5 73.67317
## 3 75.0 71.0 73.42177
## 4 75.0 70.5 73.42177
## 5 75.0 72.0 73.42177
## 6 74.0 76.5 72.91898
fit <- galton_heights %>%
lm(formula = son ~ father, data = .)
Y_hat <- predict(fit, se.fit = TRUE)
names(Y_hat)
## [1] "fit" "se.fit" "df" "residual.scale"
[][Why do we construct confidence intervals? Why are confidence
intervals important? Because confidence intervals represent the range of
scores that are likely if we were to repeat the survey, they are
important to consider when generalizing results.] https://www.google.com/search?client=firefox-b-e&q=construct+confidence+intervals
Go read the book
Comprehension Check due Jun 12, 2022 00:29 AWST # Question 1 1/1 point (graded)
The following code was used in the video to plot RSS with Beta_0 = 25.
beta1 = seq(0, 1, len=nrow(galton_heights))
results <- data.frame(beta1 = beta1,
rss = sapply(beta1, rss, beta0 = 25))
results %>%
ggplot(aes(beta1, rss)) +
geom_line() +
geom_line(aes(beta1, rss), col=2)
In a model for sons’ heights vs fathers’ heights, what is the least squares estimate (LSE) for Beta_1 if we assume Beta_0 hat is 36?
Hint: modify the code above to do your analysis. 0.65 0.5 0.2 12 correct Answer Correct: Correct. You can tell from a plot of RSS vs that the minimum estimate is 0.5
Explanation
Using the code from the video, you can plot RSS vs to find the value for that minimizes the RSS. In this case, that value is 0.5 when we assume that
is 36.
When we assumed that was 25, as in the sample code, the LSE for was 0.65.
[][Need to understand the below R code, how the blocks are put together and so on]
beta1 = seq(0, 1, len=nrow(galton_heights))
results <- data.frame(beta1 = beta1,
rss = sapply(beta1, rss, beta0 = 36))
results %>%
ggplot(aes(beta1, rss)) +
geom_line(aes(beta1, rss), col=2)
[][Residual sum of squares (RSS) measures the distance between the
true value and the predicted value given by the regression line. The
values that minimize the RSS are called the least squares estimates
(LSE)]
1/1 point (graded)
The least squares estimates for the parameters Beta_0, Beta_1, Beta_2, … Beta_n minimize the Residual Sum of Squares
correct
the residual sum of squares. You have used 1 of 1 attempt Some
1/1 point (graded)
Load the Lahman library and filter the Teams data frame to the years 1961-2001. Run a linear model in R predicting the number of runs per game based on both the number of bases on balls per game and the number of home runs per game. What is the coefficient for bases on balls? 0.39 1.56 1.74 0.027 correct Answer Correct: Correct.
Explanation
The coefficient for bases on balls is 0.39; the coefficient for home runs is 1.56; the intercept is 1.74; the standard error for the BB coefficient is 0.027.
library(broom) # tidy() function
Teams_small <- Teams %>%
filter(yearID %in% 1961:2001)
Teams_small %>%
mutate(R_per_game = R/G, BB_per_game = BB/G, HR_per_game = HR/G) %>%
do(tidy(lm(R_per_game ~ BB_per_game + HR_per_game, data = .)))
## # A tibble: 3 x 5
## term estimate std.error statistic p.value
## <chr> <dbl> <dbl> <dbl> <dbl>
## 1 (Intercept) 1.74 0.0824 21.2 7.62e- 83
## 2 BB_per_game 0.387 0.0270 14.3 1.20e- 42
## 3 HR_per_game 1.56 0.0490 31.9 1.78e-155
Teams_small <- Teams %>%
filter(yearID %in% 1961:2001)
Teams_small %>%
mutate(R_per_game = R/G, BB_per_game = BB/G, HR_per_game = HR/G) %>%
lm(R_per_game ~ BB_per_game + HR_per_game, data = .) %>%
#coef
summary # Check here, why its different with/without %>% .$coef after summary
##
## Call:
## lm(formula = R_per_game ~ BB_per_game + HR_per_game, data = .)
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.87325 -0.24507 -0.01449 0.23866 1.24218
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 1.74430 0.08236 21.18 <2e-16 ***
## BB_per_game 0.38742 0.02701 14.34 <2e-16 ***
## HR_per_game 1.56117 0.04896 31.89 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.3484 on 1023 degrees of freedom
## Multiple R-squared: 0.6503, Adjusted R-squared: 0.6496
## F-statistic: 951.2 on 2 and 1023 DF, p-value: < 2.2e-16
Teams_small <- Teams %>%
filter(yearID %in% 1961:2001)
Teams_small %>%
mutate(R_per_game = R/G, BB_per_game = BB/G, HR_per_game = HR/G) %>%
lm(R_per_game ~ BB_per_game + HR_per_game, data = .) %>%
summary %>%
.$coef
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 1.7443011 0.08235597 21.18002 7.617810e-83
## BB_per_game 0.3874238 0.02701124 14.34306 1.198143e-42
## HR_per_game 1.5611689 0.04896000 31.88662 1.777062e-155
You have used 1 of 2 attempts Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button. Answers are displayed within the problem
0.5/1 point (graded)
We run a Monte Carlo simulation where we repeatedly take samples of N = 100 from the Galton heights data and compute the regression slope coefficients for each sample:
B <- 1000
N <- 100
lse <- replicate(B, {
sample_n(galton_heights, N, replace = TRUE) %>%
lm(son ~ father, data = .) %>%
.$coef
})
lse <- data.frame(beta_0 = lse[1,], beta_1 = lse[2,])
What does the central limit theorem tell us about the variables beta_0 and beta_1?
Select ALL that apply. They are approximately normally
distributed. correct The expected value of each is the true
value of Beta_0 and Beta_1 (assuming the Galton heights data is a
complete population). Should think about this one
correct The central limit theorem does not apply in this
situation.** [][Wrong Choice, restructure your mind] It allows us to
test the hypothesis that Beta_0 = 0 and Beta_1 = 0 . partially correct
Answer Incorrect: Correct. With a large enough N
(So how much fit this large enough ? Or should I plot the histogram every time to see if its a bell curve),
the distributions of both beta_0 and beta_1 are approximately normal.
Try again. For large enough N, the central limit theorem does apply.
Explanation #
================================================================================================================================
With a large enough N, the central limit theorem applies and tells us
that the distributions of both beta_0 and beta_1 are approximately
normal. [][The expected (Expected) values of beta_0 and
beta_1 are the true values of Beta_0 and Beta_1, assuming that the
Galton heights data are a complete population.]
For hypothesis testing, we assume that the errors in the model are normally distributed. You have used 2 of 2 attempts
1/1 point (graded) Which R code(s) below would properly plot the predictions and confidence intervals for our linear model of sons’ heights?
NOTE: The function as.tibble() has been replaced by as_tibble() in a recent dplyr update.
Select ALL that apply.
galton_heights %>%
ggplot(aes(father, son)) +
geom_point(alpha = 0.3) +
geom_smooth()
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
# `geom_smooth()` using method = 'loess' and formula 'y ~ x' by default,
# scatterplot for each HR stratum
#dat %>%
# ggplot(aes(BB_per_game, R_per_game)) +
# geom_point(alpha = 0.5) +
# geom_smooth(method = "lm") +
# facet_wrap( ~ HR_strata)
data("GaltonFamilies")
galton_heights <- GaltonFamilies %>%
filter(gender == "male") %>%
select(father, childHeight) %>%
rename(son = childHeight)
galton_heights %>%
ggplot(aes(father, son)) +
geom_point() +
geom_smooth(formula= y ~ x, method = "lm")
model <- lm(son ~ father, data = galton_heights)
predictions <- predict(model, interval = c("confidence"), level = 0.95)
data <- as_tibble(predictions) %>%
bind_cols(father = galton_heights$father)
ggplot(data, aes(x = father, y = fit)) +
geom_line(color = "blue", size = 1) +
geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=0.2) +
geom_point(data = galton_heights, aes(x = father, y = son))
model <- lm(son ~ father, data = galton_heights)
predictions <- predict(model, data = galton_heights)
data <- as_tibble(predictions) %>%
bind_cols(father = galton_heights$father)
ggplot(data, aes(x = father, y = fit)) +
geom_line(color = "blue", size = 1) +
geom_point(data = galton_heights, aes(x = father, y = son))
Answer Correct: Correct. This is one way to plot predictions and confidence intervals for a linear model of sons’ heights vs. fathers’ heights. This is one of two correct answers. Correct. This code uses the predict command to generate predictions and 95% confidence intervals for the linear model of sons’ heights vs. fathers’ heights. This is one of two correct answers.
[][Explanation]
If using the geom_smooth command, you need to specify that method = “lm” in your geom_smooth command, otherwise the smooth line is a loess smooth and not a linear model.
If using the predict command, you need to include the confidence intervals on your figure by first specifying that you want confidence intervals in the predict command, and then adding them to your figure as a geom_ribbon. You have used 1 of 2 attempts Some
2.0/2.0 points (graded)
Fit a linear regression model predicting the mothers’ heights using daughters’ heights. What is the slope of the model? correct
0.31 Loading
Explanation
The following code can be used to determine the slope:
fit <- lm(mother ~ daughter, data = female_heights)
fit$coef[2]
What the intercept of the model? correct
44.2 Loading
Explanation
The following code can be used to determine the intercept:
fit$coef[1]
[][****Think about this code, how to manage put them block by block and doing what we need****]
#set.seed(1989) #if you are using R 3.5 or earlier
set.seed(1989, sample.kind="Rounding") #if you are using R 3.6 or later
## Warning in set.seed(1989, sample.kind = "Rounding"): non-uniform 'Rounding'
## sampler used
data("GaltonFamilies")
options(digits = 3) # report 3 significant digits
female_heights <- GaltonFamilies %>%
filter(gender == "female") %>%
group_by(family) %>%
sample_n(1) %>%
ungroup() %>% # Why we need the ungroup() here ??? I commented this code and below mutate() function failed
select(mother, childHeight) %>%
rename(daughter = childHeight)
female_heights %>%
#do(tidy(lm(mother ~ daughter, data = .))) # same as below code pipes
lm(mother ~ daughter, data = .) %>%
summary %>% .$coef
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 44.18 4.4105 10.02 6.20e-19
## daughter 0.31 0.0686 4.53 1.11e-05
fit <- lm(formula = mother ~ daughter, data = female_heights)
fit$coefficients
## (Intercept) daughter
## 44.18 0.31
female_heights_hat <- female_heights %>%
mutate(Y_hat = predict(lm(mother ~ daughter, data = .)))
head(female_heights_hat)
## # A tibble: 6 x 3
## mother daughter Y_hat
## <dbl> <dbl> <dbl>
## 1 67 69 65.6
## 2 66.5 65.5 64.5
## 3 64 68 65.3
## 4 64 64.5 64.2
## 5 58.5 66.5 64.8
## 6 68 69.5 65.7
2.0/2.0 points (graded)
Predict mothers’ heights using the model. What is the predicted height of the first mother in the dataset? correct
65.6 Loading
Explanation
The following code can be used to determine the height:
predict(fit)[1]
What is the actual height of the first mother in the dataset? correct
67 Loading
Explanation
The following code can be used to determine the height:
female_heights$mother[1]
#set.seed(1989) #if you are using R 3.5 or earlier
set.seed(1989, sample.kind="Rounding") #if you are using R 3.6 or later
## Warning in set.seed(1989, sample.kind = "Rounding"): non-uniform 'Rounding'
## sampler used
data("GaltonFamilies")
options(digits = 3) # report 3 significant digits
female_heights <- GaltonFamilies %>%
filter(gender == "female") %>%
group_by(family) %>%
sample_n(1) %>%
ungroup() %>%
select(mother, childHeight) %>%
rename(daughter = childHeight)
# Solution Here #########################################################################################
fit <- lm(mother ~ daughter, data = female_heights)
fit$coefficients
## (Intercept) daughter
## 44.18 0.31
predict(fit)[1]
## 1
## 65.6
female_heights$mother[1]
## [1] 67
We have shown how BB and singles have similar predictive power for scoring runs. Another way to compare the usefulness of these baseball metrics is by assessing how stable they are across the years. Because we have to pick players based on their previous performances, we will prefer metrics that are more stable. In these exercises, we will compare the stability of singles and BBs.
Before we get started, we want to generate two tables: one for 2002 and another for the average of 1999-2001 seasons. We want to define per plate appearance statistics, keeping only players with more than 100 plate appearances. Here is how we create the 2002 table:
library(Lahman)
bat_02 <- Batting %>% filter(yearID == 2002) %>%
mutate(pa = AB + BB, singles = (H - X2B - X3B - HR)/pa, bb = BB/pa) %>%
filter(pa >= 100) %>%
select(playerID, singles, bb)
2.0/2.0 points (graded)
Now compute a similar table but with rates computed over 1999-2001. Keep only rows from 1999-2001 where players have 100 or more plate appearances, calculate each player’s single rate and BB rate per stint (where each row is one stint - a player can have multiple stints within a season), then calculate the average single rate (mean_singles) and average BB rate (mean_bb) per player over the three year period. How many players had a single rate mean_singles of greater than 0.2 per plate appearance over 1999-2001? correct
46 Loading
The following code can be used to determine the number of players:
bat_99_01 <- Batting %>% filter(yearID %in% 1999:2001) %>%
mutate(pa = AB + BB, singles = (H - X2B - X3B - HR)/pa, bb = BB/pa) %>%
filter(pa >= 100) %>%
group_by(playerID) %>%
summarize(mean_singles = mean(singles), mean_bb = mean(bb))
sum(bat_99_01$mean_singles > 0.2)
How many players had a BB rate mean_bb of greater than 0.2 per plate appearance over 1999-2001? correct
3 Loading
The following code can be used to determine the number of players:
sum(bat_99_01$mean_bb > 0.2)
library(Lahman)
bat_02 <- Batting %>% filter(yearID == 2002) %>%
mutate(pa = AB + BB, singles = (H - X2B - X3B - HR)/pa, bb = BB/pa) %>%
filter(pa >= 100) %>%
select(playerID, singles, bb)
bat_01 <- Batting %>% filter(yearID %in% 1999:2001) %>%
mutate(pa = AB + BB, singles = (H - X2B - X3B - HR)/pa, bb = BB/pa) %>%
filter(pa >= 100) %>%
select(playerID, singles, bb)
length(bat_01[[1]])
## [1] 1368
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
bat_01_n1 <- bat_01 %>%
group_by(playerID) %>%
summarise_at(vars(singles, bb), list(name = mean)) %>%
filter(singles_name > 0.2)
# https://www.statology.org/r-mean-by-group/
bat_01_n1
## # A tibble: 46 x 3
## playerID singles_name bb_name
## <chr> <dbl> <dbl>
## 1 bautida01 0.200 0.0498
## 2 boggswa01 0.215 0.115
## 3 brownad01 0.203 0.107
## 4 bushho01 0.218 0.0424
## 5 cairomi01 0.211 0.0787
## 6 carusmi01 0.209 0.0364
## 7 castilu01 0.220 0.119
## 8 cedenro01 0.211 0.108
## 9 cirilje01 0.205 0.0953
## 10 delluda01 0.221 0.0919
## # ... with 36 more rows
length(bat_01_n1[[1]])
## [1] 46
bat_01_n2 <- bat_01 %>%
group_by(playerID) %>%
summarise_at(vars(singles, bb), list(name = mean)) %>%
filter(bb_name > 0.2)
# https://www.statology.org/r-mean-by-group/
# I suppose Google worth half my brain, or my brain is not functional as it should thus need Google
bat_01_n2
## # A tibble: 3 x 3
## playerID singles_name bb_name
## <chr> <dbl> <dbl>
## 1 bondsba01 0.0907 0.213
## 2 jahajo01 0.119 0.217
## 3 mcgwima01 0.0853 0.202
length(bat_01_n2[[1]])
## [1] 3
2.0/2.0 points (graded)
Use inner_join() to combine the bat_02 table with the table of 1999-2001 rate averages you created in the previous question. What is the correlation between 2002 singles rates and 1999-2001 average singles rates? correct
0.551 Loading
The following code can be used to determine the correlation:
dat <- inner_join(bat_02, bat_99_01)w
cor(dat$singles, dat$mean_singles)
What is the correlation between 2002 BB rates and 1999-2001 average BB rates? correct
0.717 Loading
The following code can be used to determine the correlation:
cor(dat$bb, dat$mean_bb)
bat_01_avg <- bat_01 %>%
group_by(playerID) %>%
summarise_at(vars(singles, bb), list(name = mean)) %>%
ungroup()
head(inner_join(bat_02, bat_01_avg, by = 'playerID'))
## playerID singles bb singles_name bb_name
## 1 abernbr01 0.180 0.0512 0.178 0.0816
## 2 abreubo01 0.148 0.1538 0.153 0.1557
## 3 agbaybe01 0.118 0.0787 0.162 0.1153
## 4 alfoned01 0.197 0.1123 0.161 0.1228
## 5 alicelu01 0.160 0.1190 0.168 0.1001
## 6 alomaro01 0.182 0.0881 0.186 0.1222
length(inner_join(bat_02, bat_01_avg, by = 'playerID')[[1]])
## [1] 392
inner_join(bat_02, bat_01_avg, by = 'playerID') %>%
summarise(cor(singles, singles_name))
## cor(singles, singles_name)
## 1 0.551
inner_join(bat_02, bat_01_avg, by = 'playerID') %>%
summarise(cor(bb, bb_name))
## cor(bb, bb_name)
## 1 0.717
1/1 point (graded)
Make scatterplots of mean_singles versus singles and mean_bb versus bb. Are either of these distributions bivariate normal? Neither distribution is bivariate normal. singles and mean_singles are bivariate normal, but bb and mean_bb are not. bb and mean_bb are bivariate normal, but singles and mean_singles are not. Both distributions are bivariate normal. correct
Both distributions are bivariate normal, as can be seen in the scatter plots made using the following code:
dat %>%
ggplot(aes(singles, mean_singles)) +
geom_point()
dat %>%
ggplot(aes(bb, mean_bb)) +
geom_point()
inner_join(bat_02, bat_01_avg, by = 'playerID') %>%
ggplot(aes(singles, singles_name)) +
geom_point(alpha = 0.3)
inner_join(bat_02, bat_01_avg, by = 'playerID') %>%
ggplot(aes(bb, bb_name)) +
geom_point(alpha = 0.3)
2/2 points (graded)
Fit a linear model to predict 2002 singles given 1999-2001 mean_singles. What is the coefficient of mean_singles, the slope of the fit? correct
0.588 Loading
The linear model and slope can be generated using the following code:
fit_singles <- lm(singles ~ mean_singles, data = dat)
fit_singles$coef[2]
Fit a linear model to predict 2002 bb given 1999-2001 mean_bb. What is the coefficient of mean_bb, the slope of the fit? correct
0.829 Loading
fit_bb <- lm(bb ~ mean_bb, data = dat)
fit_bb$coef[2]
head(inner_join(bat_02, bat_01_avg, by = 'playerID'))
## playerID singles bb singles_name bb_name
## 1 abernbr01 0.180 0.0512 0.178 0.0816
## 2 abreubo01 0.148 0.1538 0.153 0.1557
## 3 agbaybe01 0.118 0.0787 0.162 0.1153
## 4 alfoned01 0.197 0.1123 0.161 0.1228
## 5 alicelu01 0.160 0.1190 0.168 0.1001
## 6 alomaro01 0.182 0.0881 0.186 0.1222
inner_join(bat_02, bat_01_avg, by = 'playerID') %>%
lm(singles ~ singles_name, data = .) %>%
summary
##
## Call:
## lm(formula = singles ~ singles_name, data = .)
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.08380 -0.01673 -0.00108 0.01666 0.06894
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 0.06206 0.00742 8.37 1.1e-15 ***
## singles_name 0.58813 0.04511 13.04 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.0247 on 390 degrees of freedom
## Multiple R-squared: 0.304, Adjusted R-squared: 0.302
## F-statistic: 170 on 1 and 390 DF, p-value: <2e-16
inner_join(bat_02, bat_01_avg, by = 'playerID') %>%
lm(bb ~ bb_name, data = .) %>%
summary
##
## Call:
## lm(formula = bb ~ bb_name, data = .)
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.06738 -0.01695 -0.00136 0.01527 0.13777
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 0.01548 0.00391 3.96 9e-05 ***
## bb_name 0.82905 0.04076 20.34 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.0265 on 390 degrees of freedom
## Multiple R-squared: 0.515, Adjusted R-squared: 0.514
## F-statistic: 414 on 1 and 390 DF, p-value: <2e-16